Linked List
Introduction
Why need linked list?
- Unlike arrays, a linked list does not require a contiguous block of memory to store elements. Elements can be stored anywhere in memory, and through the
nextandprevpointers on node, these scattered memory blocks can be linked together to form a chain-like structure
Advantage
- Improves memory utilization efficiency, with no capacity limit (except when all memory is filled)
- Nodes can be connected or removed at any time without needing to consider resizing or moving data
Disadvantage
- Cannot quickly access elements using an index
Linked List
class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
// 输入一个数组,转换为一条单链表
ListNode createLinkedList(int[] arr) {
if (arr == null || arr.length == 0) {
return null;
}
ListNode head = new ListNode(arr[0]);
ListNode cur = head;
for (int i = 1; i < arr.length; i++) {
cur.next = new ListNode(arr[i]);
cur = cur.next;
}
return head;
}
Single Linked List
Search/Modify
- 只能用for loop由head node開始往後找,直至找到index對應的node
// 创建一条单链表
ListNode head = createLinkedList(new int[]{1, 2, 3, 4, 5});
// 遍历单链表
for (ListNode p = head; p != null; p = p.next) {
System.out.println(p.val);
}
Insertion
-
Insert a New Element at the Head of the List
// create a singly linked list
ListNode head = createLinkedList(new int[]{1, 2, 3, 4, 5});
// insert a new node 0 at the head of the singly linked list
ListNode newHead = new ListNode(0);
newHead.next = head;
head = newHead;
// now the linked list becomes 0 -> 1 -> 2 -> 3 -> 4 -> 5 -
Insert a New Element at the End of the List
- 需要transver到last node
// create a singly linked list
ListNode head = createLinkedList(new int[]{1, 2, 3, 4, 5});
// insert a new node with value 6 at the end of the linked list
ListNode p = head;
// first, go to the last node of the linked list
while (p.next != null) {
p = p.next;
}
// now p is the last node of the linked list
// insert a new node after p
p.next = new ListNode(6);
// now the linked list becomes 1 -> 2 -> 3 -> 4 -> 5 -> 6 -
Insert a New Element in the Middle of the List
- 需要找到插入位置的predecessor node
// create a singly linked list
ListNode head = createLinkedList(new int[]{1, 2, 3, 4, 5});
// insert a new node 66 after the 3rd node
// first, find the predecessor node, i.e., the 3rd node
ListNode p = head;
for (int i = 0; i < 2; i++) {
p = p.next;
}
// now p points to the 3rd node
// set the next pointer of the new node
ListNode newNode = new ListNode(66);
newNode.next = p.next;
// insert the new node
p.next = newNode;
// now the linked list becomes 1 -> 2 -> 3 -> 66 -> 4 -> 5