何时用dummy
给定链表的head结点可能最先被删除/移动? Yes-> 无脑用dummy
ListNode dummy = new ListNode(-1);
ListNode pre = dummy;
dummy.next = head;
...
return dummy.next;
反转链表
public ListNode reverseList(ListNode head){
ListNode pre = null;
ListNode cur = head;
while(cur!= null){
ListNode temp = cur.next;
cur.next = pre;
pre = cur;
cur = temp;
}
return pre;
}
计算整个链表长度
public int getLength(ListNode head){
int len = 0;
ListNode cur = head;
while(cur != null){
cur = cur.next;
len++;
}
return len;
}
快慢指针
- 找中点
- 找离end of list距离为k的点
- 找cycle
- 找intersection
ListNode slow = head;
ListNode fast = head;
/**
* Change this condition to fit specific problem.
* Attention: remember to avoid null-pointer error
**/
while (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
浙公网安备 33010602011771号