找到要插入位置節點的前驅節點。如果要在頭部插入,則它的前驅節點就是偽頭。如果要在尾部插入節點,則前驅節點就是尾節點。 通過改變 next 來插入節點。
toAdd.next = pred.next; pred.next = toAdd;
deleteAtIndex: 和插入同樣的道理。
找到要刪除節點的前驅節點。 通過改變 next 來刪除節點。
// delete pred.next? pred.next = pred.next.next;
get: 從偽頭節點開始,向前走 index+1 步。
// index steps needed?
// to move from sentinel node to wanted index
for(int i = 0; i < index + 1; ++i) curr = curr.next;
return curr.val;
全部代碼:
public class ListNode {int val;ListNode next;ListNode(int x) { val = x; }
}class MyLinkedList {int size;ListNode head; // sentinel node as pseudo-headpublic MyLinkedList() {size = 0;head = new ListNode(0);}/** Get the value of the index-th node in the linked list. If the index is invalid, return -1. */public int get(int index) {// if index is invalidif (index < 0 || index >= size) return -1;ListNode curr = head;// index steps needed // to move from sentinel node to wanted indexfor(int i = 0; i < index + 1; ++i) curr = curr.next;return curr.val;}/** Add a node of value val before the first element of the linked list. After the insertion, the new node will be the first node of the linked list. */public void addAtHead(int val) {addAtIndex(0, val);}/** Append a node of value val to the last element of the linked list. */public void addAtTail(int val) {addAtIndex(size, val);}/** Add a node of value val before the index-th node in the linked list. If index equals to the length of linked list, the node will be appended to the end of linked list. If index is greater than the length, the node will not be inserted. */public void addAtIndex(int index, int val) {// If index is greater than the length, // the node will not be inserted.if (index > size) return;// [so weird] If index is negative, // the node will be inserted at the head of the list.if (index < 0) index = 0;++size;// find predecessor of the node to be addedListNode pred = head;for(int i = 0; i < index; ++i) pred = pred.next;// node to be addedListNode toAdd = new ListNode(val);// insertion itselftoAdd.next = pred.next;pred.next = toAdd;}/** Delete the index-th node in the linked list, if the index is valid. */public void deleteAtIndex(int index) {// if the index is invalid, do nothingif (index < 0 || index >= size) return;size--;// find predecessor of the node to be deletedListNode pred = head;for(int i = 0; i < index; ++i) pred = pred.next;// delete pred.next pred.next = pred.next.next;}
}