如何对链接列表进行排序并删除任何重复的

时间:2017-05-13 21:59:09

标签: java

我有一个方法,它接收两个链表并打印出一个新的链表,这是两个传入列表的组合。我想知道如何对最终列表进行排序并删除重复项。任何帮助将不胜感激!

这是我的代码:

public static IntNode method(IntNode head1, IntNode head2){

   // create a new list that will hold the two incoming lists
   IntNode new_head = new IntNode(0, null); 
   IntNode new_node = new_head;

   for(; head1 != null; head1 = head1.link) {
       new_node.link = new IntNode(head1.data, null);
       new_node = new_node.link;
   }

   for(; head2 != null; head2 = head2.link) {
       new_node.link = new IntNode(head2.data, null);
       new_node = new_node.link;
   }

   return new_head.link;
}

1 个答案:

答案 0 :(得分:0)

我要做的第一件事是写一个方法,如果你还没有方法,将一个节点插入一个列表:

public static IntNode insertNode(IntNode head, IntNode node)
{
    node.link = null;
    if (head == null) {
        return node;
    }
    IntNode root = head;
    while (root.link != null) {
        root = root.link;
    }
    root.link = node;
    return head;
}

然后,你的merge-and-remove-duplicates例程将是这样的:

public static IntNode method(IntNode head1, IntNode head2)
{

    List<Integer> sort = new ArrayList<>();

    for (IntNode n = head1; n != null; n = n.link) {
        sort.add(n.data);
    }
    for (IntNode n = head2; n != null; n = n.link) {
        sort.add(n.data);
    }

    Collections.sort(sort);

    // run though sorted list, removing adjacent duplicates
    for (int i = 0; i < sort.size(); ++i) {
        if (i > 0 && sort.get(i) == sort.get(i - 1)) {
            sort.remove(i);
        }
    }

    // Now put the sorted, unduplicated numbers into a new list of IntNodes
    IntNode new_head = null;
    for (int data : sort) {
        IntNode newNode = new IntNode(data, null);
        new_head = insertNode(new_head, newNode);
    }
    return new_head;
}