1. 程式人生 > >2.2在單鏈表和雙鏈表中刪除倒數第K個節點

2.2在單鏈表和雙鏈表中刪除倒數第K個節點

題目

分別實現兩個函式,分別可以刪除單鏈表和雙鏈表中倒數第K個節點。

思路

兩次遍歷連結串列,第一遍每移動一步,就讓K值減1;第二遍從頭開始遍歷連結串列,每移動一步K值加1,加到0就停止遍歷,此時移動到的節點就是要刪除節點的前一個節點。

程式碼實現
class Node {
    public int value;
    public Node next;

    public Node (int data) {
        this.value = data;
    }
}

class DoubleNode {
    public
int value; public DoubleNode last; public DoubleNode next; public DoubleNode (int data) { this.value = data; } } public class RemoveLastKthNode { /** * 單鏈表 * * @param head * @param lastKth * @return */ public Node removeLastKthNode(Node head,
int lastKth) { if (head == null || lastKth < 1) { return head; } Node cur = head; while (cur != null) { lastKth--; cur = cur.next; } if (lastKth == 0) { head = head.next; } if (lastKth <
0) { cur = head; while (++lastKth != 0) { cur = cur.next; } cur.next = cur.next.next; } return head; } /** * 雙鏈表 * * @param head * @param lastKth * @return */ public DoubleNode removeLastKthDoubleNode(DoubleNode head, int lastKth) { if (head == null || lastKth < 1) { return head; } DoubleNode cur = head; while (cur != null) { lastKth--; cur = cur.next; } if (lastKth == 0) { head = head.next; head.last = null; } if (lastKth < 0) { cur = head; while (++lastKth != 0) { cur = cur.next; } DoubleNode newNext = cur.next.next; cur.next = newNext; if (newNext != null) {; newNext.last = cur; } } return head; } }