Dummy Node
When?
當linkedlist 的head可能會改變的時候
linkedlist 結構發生變化
206 Reverse list
// iterative
public ListNode reverseList(ListNode head) {
if (head == null) return head;
ListNode dummy = new ListNode(0);
dummy.next = head;
while(head.next != null){
ListNode tmp = head.next;
head.next = tmp.next;
tmp.next = dummy.next;
dummy.next = tmp;
}
return dummy.next;
}
// recursive
public ListNode reverseList(ListNode head){
if(head == null || head.next == null) return head;
ListNode p = reverseList(head.next);
// head.next 是 p 裡面的最後一個, 將 head 移到最後
head.next.next = head;
head.next = null;
return p;
}92 Reverse sublist
sublistHead 在m前一個index

25 Reverse Nodes in k-Groups
Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.
k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.
Example:
Given this linked list: 1->2->3->4->5
For k = 2, you should return: 2->1->4->3->5
For k = 3, you should return: 3->2->1->4->5
Like revers sublist
check the next k elements are valid
In while loop, just shift k-1 index, after that, shift foward preHead and tail 1 index
143 Reorder List
Given a singly linked list L: L0→L1→…→Ln-1→Ln, reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→…
Find middle
reverse tail
merge (2 ways)
82 Remove all duplicates
要比較第一個node, head 退回成為dummy
86 Partition
Partition linkedList based on value x, < on the left, >= on the right
Create left and right node, as well as 2 leftHead and rightHead dummy nodes.
Sort List
Use the merge sort
findMiddleandmergemethod
328. Odd Even Linked List
Given a singly linked list, group all odd nodes together followed by the even nodes. Please note here we are talking about the node number and not the value in the nodes.
You should try to do it in place. The program should run in O(1) space complexity and O(nodes) time complexity.
Last updated
Was this helpful?