gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 08:54:41 25 4
gpt4 key购买 nike

如何在向列表添加项后打印链表的内容?

我编写了链表,我尝试在链表中间添加一个值。添加后还得看链表的内容。

我该怎么做?

代码如下:

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);
}
}

代码中可能会有一些错误。如果我错了,请纠正我。

最佳答案

看到您需要更改您的 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个5个79

关于java - 将项目添加到列表后打印链表的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20878245/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com