删除链表中的节点而不删除适当的节点

时间:2018-06-26 00:17:29

标签: java linked-list

我在这里开始了此问题的基础,并被告知开始一个新线程:Delete elements within a Linked List

我在下面完成了我的代码:

public class MyLinked {
    static class Node {
        public Node (double item, Node next) { this.item = item; 
this.next = next; }
        public double item;
        public Node next;
        } 
    int N;
    Node first;
public void delete (int k) {
        if (k < 0 || k >= N) throw new IllegalArgumentException ();

        if (k == 0) {
            Node temp = first;
            first = first.next;
            temp.next = null;
        }else { 
            Node previous = first;
            while (k < N -1) {
                previous = previous.next;
                k++;
            }

        Node current = previous.next;
        previous.next = current.next;
        current.next = null;
        N--;
        }
    }

我认为我指的是删除第k个元素的适当节点,但是,这是测试返回的内容:

[ 11 21 31 41 ].delete( 0 ): Expected 4 nodes, but got less.
[ 11 21 31 41 ].delete( 1 ): expected=[ 11 31 41 ], actual=[ 11 21 31 ]
[ 11 21 31 41 ].delete( 3 ): expected=[ 11 21 31 ], actual=[ 11 31 41 ]
[ 11 21 31 41 51 ].delete( 0 ): Expected 5 nodes, but got less.
[ 11 21 31 41 51 ].delete( 1 ): expected=[ 11 31 41 51 ], actual=[ 11 21 31 41 ]
[ 11 21 31 41 51 ].delete( 2 ): expected=[ 11 21 41 51 ], actual=[ 11 21 31 51 ]
[ 11 21 31 41 51 ].delete( 3 ): expected=[ 11 21 31 51 ], actual=[ 11 21 41 51 ]
[ 11 21 31 41 51 ].delete( 4 ): expected=[ 11 21 31 41 ], actual=[ 11 31 41 51 ]

我认为错误是,当它试图删除[0]时,它是在[1]处删除,而在[1]是[2]处删除。我想它是从[1]开始而不是[0]作为列表中的第一个节点?非常感谢您提供有关如何调整我的代码以使其正确阅读的帮助。

这是测试代码:

 private static void testDelete (int k, String list, String expected) {
        MyLinked actual = MyLinked.of (list);
        String message = String.format ("[ %s ].delete( %d )", list, 
k);
        try {
            actual.delete (k);
        } catch (Throwable e) {
            String exception = e.getClass ().getName ();
            if (! exception.equals (expected)) {
                e.printStackTrace (); // for debugging
                showError (String.format ("%s: expected=%s, 
actual=%s", message, expected, exception));
            }
            return;
        }
        check (message, actual, expected);
    }

1 个答案:

答案 0 :(得分:0)

我能够调整代码并获得正确答案。工作代码如下:

    public void delete (int k) {
        if (k < 0 || k >= N) throw new IllegalArgumentException ();

        if (k == 0) {
            Node temp = first;
            first = first.next;
            temp.next = null;
            N--;
        }
        else {  
            Node previous = first;
            int count = 0;
            while (count < k-1) {
                previous = previous.next;
                count++;
            }

        Node current = previous.next;
        previous.next = current.next;
        current.next = null;
    N--;
        }
   }

我添加了int count并将计数器设置为从0开始。当我将其从1开始时,这就是为什么它删除了错误的值。

如果列表仅包含一个元素并且该元素被删除,我还需要在函数的(k == 0)部分中添加N--以调整列表的大小。