簡體   English   中英

用 hashmap JAVA 確定兩個有序鏈表之間的共同項

[英]Determine the common items between two sorted linked lists with hashmap JAVA

我使用哈希表來查找兩個鏈表之間的交集。 不過,問題是我必須事先給出表格大小,如果表格大小是 > 交集元素,則表格將首先填充元素,然后打印 0(k 是哈希表的大小),如下所示:

輸出:常見項目有:2 5 6 0 0 0 0

import java.util.*;

public class LinkedList {
Node head;

static class Node {
    int data;
    Node next;

    Node(int d) {
        data = d;
        next = null;

    }

}

public void printList() {
    Node n = head;
    while (n != null) {
        System.out.print(n.data + " ");
        n = n.next;
    }
}

public void append(int d) {

    Node n = new Node(d);

    if (head == null) {
        head = new Node(d);
        return;
    }

    n.next = null;
    Node last = head;
    while (last.next != null) {
        last = last.next;
    }
    last.next = n;
    return;

}

static int[] intersection(Node tmp1, Node tmp2, int k) {
    int[] res = new int[k];

    HashSet<Integer> set = new HashSet<Integer>();
    while (tmp1 != null) {

        set.add(tmp1.data);
        tmp1 = tmp1.next;

    }

    int cnt = 0;

    while (tmp2 != null) {
        if (set.contains(tmp2.data)) {
            res[cnt] = tmp2.data;
            cnt++;
        }
        tmp2 = tmp2.next;

    }

    return res;

}

public static void main(String[] args) {
    LinkedList ll1 = new LinkedList();
    LinkedList ll2 = new LinkedList();


    ll1.append(1);
    ll1.append(2);
    ll1.append(3);
    ll1.append(4);
    ll1.append(5);
    ll1.append(6);
    ll1.append(7);
    ll1.append(8);

    ll2.append(0);
    ll2.append(2);
    ll2.append(5);
    ll2.append(6);
    ll2.append(9);
    ll2.append(10);
    ll2.append(13);
    ll2.append(14);

    System.out.println("The Linked List 1 size is:  ");


    int[] arr = intersection(ll1.head, ll2.head, 7);

    System.out.print("The Linked List 1 items are: ");
    ll1.printList();

    System.out.print("\nThe Linked List 2 items are: ");
    ll2.printList();

    System.out.print("\nThe Common items are: ");
    for (int i : arr) {
        System.out.print(i + " ");
    }

}}

不要使用數組- 而是使用(甚至返回)您的 LinkedList 的實例(或 Java 的List實例)。 稍后您可以根據需要輕松地將列表轉換為數組(在 Java中將列表轉換為數組)

請注意,相乘的零並不是您遇到的最大問題 - 最大的問題是您實際上無法理解第一個零只是空元素還是實際上是作為交集部分的0元素

您可以通過將列表推入兩個Set並使用retainAll來減少自己的代碼

Set<Integer> set1 = new HashSet<Integer>();
while (tmp1 != null) {
    set1.add(tmp1.data);
    tmp1 = tmp1.next;
}
// now all data of your list 1 is stored in set1
Set<Integer> set2 = new HashSet<Integer>();
while (tmp2 != null) {
    set2.add(tmp2.data);
    tmp2 = tmp2.next;
}
// now all data of your list 2 is stored in set2
set1.retainAll(set2);
// now only duplicates are stored in set1

注1:重新分配參數是不好的做法,我更喜歡新的局部變量

注2:擺脫數組,你發現了他們的問題之一

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM