1. 程式人生 > >刪除連結串列的倒數第K個節點(每日一道演算法題)

刪除連結串列的倒數第K個節點(每日一道演算法題)

單向連結串列,刪除它的倒數第K個節點

//節點類
package LinkedList;

/**
 * @author:MindMrWang
 *2017年11月22日
 *:function:連結串列節點
 */
public class Node {
    public int value;
    public Node next;
    public Node() {

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

}
public static Node remove(Node head,int
k) { if(head==null||k<1) {//當head為空或者K<1,說明沒有倒數第K個節點。 throw new RuntimeException("your LinkedList has none the last k Node"); } Node cur = head; while(cur != null) {//從第一個節點開始遍歷,若不為空,k-- k--; cur = cur.next; } if
(k>0) { throw new RuntimeException("your LinkedList has none the last k Node"); } if(k==0) { head = head.next;//如果k為零,那麼倒數第k個元素就是頭結點,所以將頭結點去除,將head指向head.next } if(k<0) {//當K小於零的時候我們想要刪除倒數第k個節點,就要知道第N-k個節點(倒數第K個節點的前一個節點) cur = head;//第一次遍歷cur位置改變了,所以要重新賦值
while(++k != 0) {//我們第一次遍歷的時候K為k-N,它和N-k為相反數,所以將節點進行第二次從頭結點遍歷 cur = cur.next; //每次遍歷加1,當它K為0的時候他就移動到了N-k的位置不用 } cur.next = cur.next.next; } return head; }

雙向連結串列,刪除它的倒數第K個節點

package LinkedList;

/**
 * @author:MindMrWang
 *2017年11月22日
 *:function:雙向節點
 */
public class DoubleNode {
    int value;
    DoubleNode last;
    DoubleNode next;
    public DoubleNode(int data) {
        this.value = data;
    }
}

//這個是雙向連結串列的刪除方法,大體思路和上面相同
public static DoubleNode remove2(DoubleNode head,int k) {
        if(head==null||k<1) {//當head為空或者K<1,說明沒有倒數第K個節點。
            throw new RuntimeException("your LinkedList has none the last k Node");
        }

        DoubleNode cur = head;
        while(cur != null) {//從第一個節點開始遍歷,若不為空,k--
            k--;
            cur = cur.next;
        }

        if(k>0) {
            throw new RuntimeException("your LinkedList has none the last k Node");
        }

        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.next = cur;
            }
        }


        return head;

    }

引數書籍《程式設計師程式碼面試指南》