【问题标题】:How to create 2 different linked list and print the intersection of both the linked list如何创建2个不同的链表并打印两个链表的交集
【发布时间】:2015-05-23 16:35:25
【问题描述】:
import java.util.*;
public class Intersection
{
private Node head;
private Node head1;
private Node head2;
private Node current1;
private Node current2;
private int l1;
private int l2;

public Intersection()
{
head= new Node(null);
head1= new Node(null);
head2= new Node(null);
Node current1= head1;
Node current2= head2;
l1=0;l2=0;
}

public static void main(String[] args)
{
Intersection obj= new Intersection(); 
LinkedList<Object> list1 = new LinkedList<Object>();
LinkedList<Object> list2 = new LinkedList<Object>(); 
list1.add(3);
list1.add(6);
list1.add(9);
list1.add(15);
list1.add(30);
list2.add(10);
list2.add(15);
list2.add(30);
Object ans= obj.method(obj.head1, obj.head2);
System.out.println(ans);
}


public Object method(Node current1, Node current2)
{
int diff;

if(current1== null || current2== null)
{
    return null;
}

while(current1.getNext() != null)
{
   l1++;
   current1=current1.getNext();
}

while(current2.getNext() != null)
{
   l2++;
   current2=current2.getNext();
}

if(l1>l2)
{
    diff=l1-l2;
    int j=0;
    while(j<diff)
    {
        current1=current1.getNext();
        j++;
    }
}

else
{
    diff=l2-l1;
    int j=0;
    while(j<diff)
    {
        current2=current2.getNext();
        j++;
    }
}

 while(current1!= null || current2!= null)
 {
    if(current1.getData()==current2.getData())
        return current1.getData();
    current1=current1.getNext();
    current2=current2.getNext();
}
return null;
}

private class Node
{
Node next;
Object data;

public Node(Object _data)
{
 next= null;
 data= _data;
}

public Node(Node _next, Object _data)
{
next= _next;
data= _data;
}

public Object getData()
    {
        return data;
    }

    public void setData(Object _data)
    {
        data = _data;
    }

    public Node getNext()
    {
        return next;
    }

    public void setNext(Node _next)
    {
        next = _next;
    }
}
}

上面是我的代码,用于找出没有错误的链表的交集。 我在如何创建 2 个不同的链表然后打印链表的交集时遇到问题。 请给点建议。

【问题讨论】:

  • 为什么要实现自己的列表而不是使用内置的集合类? List 类的定义在哪里? list1list2 的声明在哪里?任何人都很难帮助您处理不完整的代码。但是,在这里发布所有代码并说“请为我调试”是不可接受的。您需要努力找出您不理解的内容并提出更具体的问题。
  • 我已经编辑了我的代码,现在我已经声明了 list1 和 list2。

标签: java singly-linked-list


【解决方案1】:

这是创建 LinkedList 的方法,其中 Object 是您将在列表中保存的类型:

LinkedList<Object> list1 = new LinkedList<Object>();

创建第二个 LinkedList:

 LinkedList<Object> list2 = new LinkedList<Object>();

之后你有两个列表:list1 和 list2,这是你需要的吗?

路口:

list1.retainAll(list2);

和 list1 会有交集:)

【讨论】:

  • 你没关系......!!!!!!我也想打印出点赞列表的交集元素???那么,我应该如何将头节点传递给我的公共对象方法()
  • 我刚刚编辑了我的代码。它给我的答案是 null 而不是 15。请给出一些建议为什么会这样???
  • 您应该能够追踪代码并找出原因。
  • 我认为我的 head1 和 head2 节点为空。但是我对如何将我的 head1 设置为 3 和 head2 设置为 10 有疑问,
猜你喜欢
  • 2021-01-03
  • 1970-01-01
  • 2021-10-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-19
  • 2018-07-23
  • 1970-01-01
相关资源
最近更新 更多