算法 - 鏈表操做題目套路 前面這一篇文章主要講鏈表操做時候的實操解決方式,本文從本質講解鏈表操做的元信息,學完後,不再怕鏈表操做題目了。算法
1.鏈表的基本操做
鏈表的基本操做無外乎插入,刪除,遍歷大數據
插入的化,要考慮到前驅節點和後繼節點,記住下面的僞代碼url
nex = 當前節點.next 當前節點.next = 插入的指針 插入指針.next = tmp
對於刪除,是否會以爲須要備份一下next的指針,答案是不用,執行語句是先取右邊的值存起來而後賦值給左邊的,因此直接下面一句話便可.net
cur.next = cur.next.next
對於遍歷,其實是又迭代和遞歸的,另外又有前序和後序指針
cur = head while cur != null { print(cur) cur = cur.next } //前序 dfs(cur) { if cur == null return print(cur.val) return dfs(cur.next) }
2.鏈表的考點
鏈表的考點就只有對指針的修改和對指針的拼接,其中都須要對指針的前驅節點和後繼節點進行保留,若是頭節點不能首次肯定,或者可能會改變,那麼又須要一個虛擬頭節點,鏈表的考點無外乎就這些。code
下面咱們來看兩個題遞歸
刪除鏈表中的重複元素leetcode
https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list-ii/開發
public ListNode deleteDuplicates(ListNode head) { //遞歸版 if (head == null || head.next == null) return head; if (head.val == head.next.val) { while (head.next != null && head.next.val == head.val) head = head.next; head = deleteDuplicates(head.next); } else { head.next = deleteDuplicates(head.next); } return head; }
判斷是否爲迴文鏈表rem
https://leetcode-cn.com/problems/palindrome-linked-list/
public boolean isPalindrome(ListNode head) { if(head == null || head.next == null)return true; temp = head; return dfs(head); } public boolean dfs(ListNode head){ if(head == null)return true; boolean res = dfs(head.next) && temp.val == head.val; temp = temp.next; return res; }
總結,鏈表的題目,掌握號指針的操做,就會簡單點了,對於遞歸寫法也會簡化不少代碼 大數據開發,更多關注查看我的資料