If there are two middle nodes, return the second middle node.
If there are two middle nodes, return the first middle node.
Find the Nth Element
Dummy Node
Merge Two Sorted Lists
Iterative
Recursive
Remove Linked List Elements
Remove all elements from a linked list of integers that have value val.
Iterative
Recursive
Linked List Has Cycle
Two Pointer Technique in Linked List 链表中的两个指针
For Linked List, we can use two-pointer technique:
Two pointers are moved at different speed: one is faster while another one might be slower.
The scenario, which is also called slow-pointer and fast-pointer technique, is really useful.
Detect Cycles in Linked List
If there is no cycle, the fast pointer will stop at the end of the linked list.
If there is a cycle, the fast pointer will eventually meet with the slow pointer.
The proper speed for the two pointers?
Slow pointer - One step at a time
Fast pointer - Two steps at a time
链表中快慢指针的Template
Tips
1. Always examine if the node is null before you call the next field.
总是检查节点是否为null,否则node.next会导致null-pointer错误
Getting the next node of a null node will cause the null-pointer error. For example, before we run fast = fast.next.next, we need to examine both fast and fast.next is not null.
2. Carefully define the end conditions of your loop.
仔细检查循环结束的条件,避免出现死循环
Run several examples to make sure your end conditions will not result in an endless loop. And you have to take our first tip into consideration when you define your end conditions.
public ListNode removeElements(ListNode head, int val) {
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode curr = head;
ListNode prev = dummy;
while (curr != null) {
if (curr.val == val) {
prev.next = curr.next;
} else {
prev = prev.next;
}
curr = curr.next;
}
return dummy.next;
}
public ListNode removeElements(ListNode head, int val) {
if (head == null) return null;
head.next = removeElements(head.next, val);
return head.val == val ? head.next : head;
}
public Boolean hasCycle(ListNode head) {
if (head == null || head.next == null) {
return false;
}
ListNode fast, slow;
fast = head.next;
slow = head;
while (fast != slow) {
if(fast==null || fast.next==null)
return false;
fast = fast.next.next;
slow = slow.next;
}
return true;
}
// Initialize slow & fast pointers
ListNode slow = head;
ListNode fast = head;
/**
* Change this condition to fit specific problem.
* Attention: remember to avoid null-pointer error
**/
while (slow != null && fast != null && fast.next != null) {
slow = slow.next; // move slow pointer one step each time
fast = fast.next.next; // move fast pointer two steps each time
if (slow == fast) { // change this condition to fit specific problem
return true;
}
}
return false; // change return value to fit specific problem