程序媛詹妮弗
终身学习

 

何时用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

  

posted on 2020-12-30 12:17  程序媛詹妮弗  阅读(125)  评论(0编辑  收藏  举报