为什么我的方法removeDuplicates()返回没有重复项的链接列表?

问题描述 投票:-1回答:1

当我尝试实现一个删除重复项的方法时,它返回链接列表,副本仍然存在。我不确定它是变量赋值的问题还是我创建的show()方法。

https://www.dropbox.com/s/2cjj4nb4v8i5fg9/RemoveDuplicates.zip?dl=0

public class LinkedList {
    LinkedListNode head;

    //generating add method to 
    public void add(int data) {
        LinkedListNode newNode = new LinkedListNode();
        newNode.data = data;
        newNode.next = null;

        if (head == null) {
            head = newNode;
        }
        else {
            LinkedListNode current = head;
            while(current.next != null) {
                current = current.next;
            }
            current.next = newNode;
        }
    }
    public void show() {
        LinkedListNode newNode = head;

        while(newNode.next != null) {
            System.out.println(newNode.data);
            newNode = newNode.next;
        }
        System.out.println(newNode.data);

    }
}

public class Test {


    public static void main(String[] args) {
        LinkedListNode head = new LinkedListNode();

        //12 and 5 are duplicates
        LinkedList list = new LinkedList();
        list.add(5);
        list.add(45);
        list.add(12);
        list.add(12);
        list.add(5);
        list.add(33);
        list.add(12);
        list.add(45);

        list.show();

        removeDuplicates(head);

        list.show();
    }

    public static void removeDuplicates(LinkedListNode head) {

        LinkedListNode current = head;
        LinkedListNode runner = null;


        while (current != null) {
            runner = current;
            while (runner.next != null) {
                if (runner.next.data == current.data) {
                    runner.next = runner.next.next;
                }
                else {
                    runner = runner.next;
                }

            }
            current = current.next;

        }

    }
}
java duplicates singly-linked-list
1个回答
2
投票

主方法中的head与链表中的head不同。

主方法中的head总是空的,你根本就没有修改list

© www.soinside.com 2019 - 2024. All rights reserved.