題目:
分別實現兩個函數,一個可以刪除單鏈表中倒數第K個節點,另一個可以刪除雙鏈表中倒數第K個節點
思路:
如果鏈表爲空或者K值小於1的情況下,直接返回鏈表。否則讓鏈表從頭往後走,沒走一步,K值減一,有一下幾種情況
鏈表爲1-2-3-4-5,K值爲6
很顯然,鏈表不存在倒數第六個節點
鏈表爲1-2-3-4-5,K值爲5
倒數第5個節點爲1節點
鏈表爲1-2-3-4-5,K值爲3
倒數第三個節點爲3
分析可得:
當K值大於鏈表長度時候,直接返回即可,當K值等於鏈表長度,相當於刪除頭結點,直接head指向next即可,當K大於0小於鏈表長度,進一步分析,假設鏈表長度爲爲N,倒數的值爲K,要刪除倒數第K個點,只需要找到他的前一個節點即可,倒數第K個節點的前一個節點就是N-K,第一次遍歷結束,K的值變成K-N,第二次遍歷時候,K的值不斷+1,當K=0時,就是K的前一個節點。
public class test2 { public class Node { private Node next; private Node last; private int value; public Node(int value) { this.value = value; } } public Node change(Node head,int k){ if (head == null || k < 1) return head; Node cur = head; while (cur != null){ k--; cur = cur.next; } return head; } public Node deleteKth(Node head,int k){ change(head,k); Node cur = head; if (k == 0){ head = head.next; } if (k < 0){ cur = head; while (++k != 0){ cur = cur.next; } cur.next = cur.next.next; } return head; } public Node deleteDoubleKth(Node head,int k){ change(head, k) Node cur = head; if (k == 0){ head = head.next; head.last = null; } if (k < 0){ cur = head; while (++k !=0){ cur = cur.next; } cur.next = cur.next.next; if (cur.next != null){ cur.next.last = cur; } } return head; } }