如何创建2个不同的链表并打印两个链表

时间:2015-05-23 16:35:25

标签: java singly-linked-list

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个不同的链表然后打印链表的交集时遇到问题。 请提出一些建议。

1 个答案:

答案 0 :(得分:0)

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

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

创建第二个LinkedList:

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

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

路口:

list1.retainAll(list2);

和list1将有交集:)