最近花了幾天時間,將鏈表題除帶鎖外的題目做完了,下面對鏈表題部分題目進行總結和分析。
鏈表題目解決方法
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
1669 Merge In Between Linked List
2. 鏈表反轉
3. 快慢指針