将项目添加到列表后打印链接列表的内容

时间:2014-01-02 07:23:56

标签: java linked-list

如何在将项目添加到列表后打印链接列表的内容?

我编写了链接列表,我尝试在列表中间添加一个值。 添加后我必须看到链表的内容。

我该怎么做?

以下是代码:

public class LinkedList {
    int item;
    LinkedList next;

    public LinkedList()  // null constructor 
    { }

    // constructor to add pass the item and next value
    public LinkedList(int item,LinkedList next) 
    {
        this.item= item;
        this.next= next;
    }

    // constructor for items with null reference ie. the last element
    public LinkedList(int item) 
    {
        this(item,null);
    }

    // inserting an item in the linkedlist
    // (this assigns old reference to the new items next)
    public void additem(int item) 
    {
        this.next = new LinkedList(item,next);
    }

    public static void main(String args[])
    {
        LinkedList l1 = new LinkedList();
        LinkedList l2 = new LinkedList();
        LinkedList l3 = new LinkedList();
        LinkedList l4 = new LinkedList();
        l1.item = 3;
        l1.next = l2;
        l2.item = 5;
        l2.next = l3;   
        l3.item = 7;
        l3.next = l4;
        l4.item = 9;
        l4.next = null;

        System.out.println(l1);

        // inserting an item after l1 (so l1 points to the newly added value 
        // and the new one gets the nxt items refernce)
        l1.additem(8);
    }
}

也许代码中会出现一些错误。如果我错了,请纠正我。

2 个答案:

答案 0 :(得分:0)

我认为你的additem方法不正确。在这里你无法插入该项目。检查语法。

public void additem(int item) 
{
Linkedlist node = new Linkedlist(item);
node.next = this.next;
this.next =node;

}

请阅读: - http://www.softwareandfinance.com/Java/Singly_Linked_List.html

答案 1 :(得分:0)

看到您需要更改additem类并定义遍历方法。

您需要传递旧节点的add item方法,在该节点之后插入新节点并返回旧节点并重新分配它。

您必须手动从一个元素遍历到另一个元素的遍历方法。

public static LinkedList additem(LinkedList l1,int item) //inserting an item in the linkedlist (this assigns old reference to the new items next)
{
LinkedList l2=new LinkedList(item,l1.next);
l1.next = l2;
return l1;

}

public static void traverse( LinkedList l1){
    do{
        System.out.println(l1.item);
        if(l1.next!=null){
            l1=l1.next;
        }
    }while(l1.next!=null);
     System.out.println(l1.item);
}

public static void main(String args[])
{
    LinkedList l1 = new LinkedList();
    LinkedList l2 = new LinkedList();
    LinkedList l3 = new LinkedList();
    LinkedList l4 = new LinkedList();
    l1.item = 3;
    l1.next = l2;
    l2.item = 5;
    l2.next = l3;   
    l3.item = 7;
    l3.next = l4;
    l4.item = 9;
    l4.next = null;

    //traverse(l1);

    l1=additem(l1,8); // inserting an item after l1 (so l1 points to the newly added value and the new one gets the nxt items refernce)
     traverse(l1);
}

输出 3 8 五 7 9