LeetCode 鏈表題總結

     

最近花了幾天時間,將鏈表題除帶鎖外的題目做完了,下面對鏈表題部分題目進行總結和分析。

鏈表題目解決方法

1、鏈表反轉

2、快慢指針

鏈表反轉模板

ListNode cur = head.next;
head.next = null;
while (cur != null) {
       ListNode next = cur.next;
       cur.next = head;
       head = cur;
       cur = next;
}

快慢指針模板

 

 

 

ListNode slow = head;
ListNode fast = head;
ListNode prev = slow;
while(fast != null && fast.next != null){
   prev =slow;
   slow = slow.next;
   fast = fast.next.next;
}

      遇到一些需要找到鏈表的中點問題時,可能會有鏈表長度爲奇數或者偶數的情況,當長度爲偶數時,模板裏面 prev 爲第一個中點,slow 爲第二個中點,長度爲奇數時 ,slow 爲鏈表的中點。

部分題目分類

 1. 簡單題

 1290 Convert Binary Number in a Linked List to Integer

 237 Delete Node in a Linked List

 21 Merge Two Sorted Lists

1669 Merge In Between Linked List

 

 2. 鏈表反轉

 206 Reverse Linked List

 24 Swap Nodes in Pairs

 92 Reverse Linked List II

 25 Reverse Nodes in k-Group

 

 3. 快慢指針

 876  Middle of the Linked List

 141 Linked List Cycle

 142 Linked List Cycle II

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章