代码随想录一刷-Day03
LeetCode203.移除链表元素
没什么好说的,用虚拟头节点做:
public ListNode removeElements(ListNode head, int val) {
if (head == null) {
return head;
}
// 建立虚拟头节点
ListNode dummyHead = new ListNode(-1);
dummyHead.next = head;
ListNode cur = head;
ListNode pre = dummyHead;
while (cur != null) {
if (cur.val == val) {
pre.next = cur.next;
cur = pre.next;
} else {
pre = cur;
cur = cur.next;
}
}
return dummyHead.next;
}
LeetCode707.设计链表
要严谨,要细心
class MyLinkedList {
static class Node {
int val;
Node next;
Node (int val, Node next) {
this.val = val;
this.next = next;
}
}
Node dummyHead;
int size;
public MyLinkedList() {
dummyHead = new Node(-1, null);
size = 0;
}
private Node getNode(int index) {
if (index == -1) {
return dummyHead;
}
if (index < 0 || index >= size) {
return null;
}
Node cur = dummyHead.next;
int i = 0;
while (cur != null) {
if (i == index) {
break;
}
i++;
cur = cur.next;
}
return cur;
}
public int get(int index) {
Node node = getNode(index);
return node == null ? -1 : node.val;
}
public void addAtHead(int val) {
Node newNode = new Node(val, dummyHead.next);
dummyHead.next = newNode;
size++;
}
public void addAtTail(int val) {
Node newNode = new Node(val, null);
Node cur = dummyHead;
while (cur.next != null) {
cur = cur.next;
}
cur.next = newNode;
size++;
}
public void addAtIndex(int index, int val) {
Node node = getNode(index - 1);
if (node != null) {
Node newNode = new Node(val, node.next);
node.next = newNode;
size++;
}
}
public void deleteAtIndex(int index) {
Node preNode = index == 0 ? dummyHead : getNode(index - 1);
if (preNode != null) {
Node delNode = getNode(index);
if (delNode == null) {
preNode.next = null;
} else {
preNode.next = delNode.next;
size--;
}
}
}
}
LeetCode206.反转链表
Nothing to say
public ListNode reverseList(ListNode head) {
if(head == null) {
return head;
}
ListNode dummyHead = new ListNode();
dummyHead.next = head;
ListNode pre = head;
ListNode cur = head.next;
while (cur != null) {
ListNode temp = cur.next;
cur.next = pre;
pre = cur;
cur = temp;
}
if (dummyHead.next != null) {
dummyHead.next.next = null;
}
return pre;
}
时间复杂度:O(n)
空间复杂度:O(1)