从链接列表的末尾删除Kth节点

时间:2016-03-17 04:47:22

标签: java linked-list

除了我要删除列表if (kthToLast == 0) head = head.next;中的第一个节点时,一切正常。我不知道为什么它不会删除第一个元素,因为head = head.next;应该工作。

感谢。

// 2.2 Implement an algorithm to find the kth to last element of a singly linked list.

public class RemoveKthToLast {

    static Node head;
    static int count = 0;

    public static class Node {
        int data;
        Node next;

        Node(int data) {
            this.data = data;
            next = null;
            count++;
        }
    }

    public Node removeKthToLast(Node head, int n) {
        if (head == null || n < 1)
            System.out.println("invalid");;

        int count = 0;
        Node temp = head;
        while (temp != null) { // count number of nodes in list
            temp = temp.next;
            count++;
        }

        if (n > count)
            System.out.println("n is greater than length of list");;

        int kthToLast = count - n;

        // remove first node 
        if(kthToLast == 0) 
             head = head.next;

        for (int i = 0; i < kthToLast - 1; i++) 
            head = head.next;

        head.next = head.next.next;
        return head;
    }

    // prints out contents of linked-list
    public void toString(Node node) {
        while (node != null) {
            System.out.print(node.data + " ");
            node = node.next;
        }
    }

    public static void main(String args[]) {

        RemoveKthToLast list = new RemoveKthToLast();

        list.head = new Node(1);
        list.head.next = new Node(2);
        list.head.next.next = new Node(3);
        list.head.next.next.next = new Node(4);

        list.removeKthToLast(head, 0);
        list.toString(head);
    }
}

3 个答案:

答案 0 :(得分:0)

如果唯一的问题是没有删除第一个节点,那么试试这个

// remove first node 
if(kthToLast == 0) {
     head = head.next;
     return head;
}

答案 1 :(得分:0)

问题在于,即使您尝试删除链接列表中的第一个节点,仍然会继续执行该方法的其余部分,该方法只应在尝试删除第一个节点以外的节点时执行。例如,假设您正试图移除头部。是的,头字段会更新到列表中的第二个节点。但是,该方法不会在那里结束并执行行head.next = head.next.next,这将错误地删除链表中的第3个节点。因此,解决方案是在头区域重置后基本结束方法。

public Node removeKthToLast(Node head, int n) {
    if (head == null || n < 1)
        System.out.println("invalid");;

    int count = 0;
    Node temp = head;
    while (temp != null) { // count number of nodes in list
        temp = temp.next;
        count++;
    }

    if (n > count)
        System.out.println("n is greater than length of list");;

    int kthToLast = count - n;

    // remove first node 
    if(kthToLast == 0){
         head = head.next;
         return head;//end the method here when removing the 1st node
    }
    for (int i = 0; i < kthToLast - 1; i++) 
        head = head.next;

    head.next = head.next.next;
    return head;
    }

另外,请确保更新主要列表中的头节点。

list.head = list.removeKthToLast(head,4);

答案 2 :(得分:0)

只是一个建议:你可以在这里使用递归函数,你的代码将非常简单:

PSEXEC -u storeadmin -p ('"' + ($x -replace '"', '\"') + '"') \\srXXX01 cmd /c TIME /T