gpt4 book ai didi

java - 打印反向链表时出现问题(java)

转载 作者:行者123 更新时间:2023-12-01 04:18:32 25 4
gpt4 key购买 nike

基本上,我创建了打印整数链接列表、从链接列表中删除重复项以及反转链接列表的方法。一切工作正常......几乎。出于某种原因,我无法让我的 printLinked() 方法在列表反转后工作。目前,我只是创建了一个 while 循环来输出反转的列表,这样我至少可以确定列表正在反转。不过,我需要让 printLinked() 方法执行此操作。如果有人可以帮助我或为我指出正确的方向来找出问题所在,那么我将非常感激。谢谢。

    import java.util.Scanner;

公共(public)类ListTest {

public static void main (String[] args)
{
ListNode head = new ListNode();
ListNode tail = head;
tail.link = null;

int input;

Scanner keyboard = new Scanner (System.in);

System.out.println("Enter integers into list; end by entering a zero");
input = keyboard.nextInt();

ListNode temp;

while (input != 0)
{

temp = new ListNode();
temp.data = input;
temp.link = null;
tail.link = temp;
tail = temp;

input = keyboard.nextInt();


}

System.out.println("You entered the following integers : ");
printLinked(head.link);

delrep(head);
System.out.println("After deleting repeating integers, you are left with : ");
printLinked(head.link);


System.out.println("Your inverted list of integers is now : ");
invert(head);

printLinked(head.link);








}


public static void printLinked(ListNode list)
{
ListNode cursor = list;

while (cursor != null)
{

System.out.print(cursor.data + " ");
cursor = cursor.link;
}



System.out.println("");


}


public static void delrep(ListNode head)
{

ListNode temp = new ListNode();




while(head != null)
{
temp = head;

while(temp.link != null)
{
if(head.data == temp.link.data)
{
ListNode temp2 = new ListNode();
temp2 = temp.link;
temp.link = temp2.link;
temp2 = null;
}
else
{
temp = temp.link;
}
}

head = head.link;
}

}


public static void invert(ListNode head)
{

ListNode temp1 = null;
ListNode temp2 = null;


while (head != null)
{
temp1 = head.link;
head.link = temp2;
temp2 = head;
head = temp1;



}

head = temp2;





//This portion of code needs to be removed. I added this part just so I can visually
//confirm that the list is reversing until I can get the print method to work for the
// reversed list.

while (head.link != null)
{
System.out.print(head.data + " ");
head = head.link;
}
System.out.println("");


}

}

另外,这就是我的 ListNode 类:

    public class ListNode

{

public int data;
public ListNode link;

}

最佳答案

您需要在反转方法中返回列表的新头:

public static ListNode invert(ListNode head) {
ListNode temp1;
ListNode temp2 = null;

while (head != null) {
temp1 = head.link;
head.link = temp2;
temp2 = head;
head = temp1;
}

return temp2;
}

并在打印时使用返回值:

System.out.println("Your inverted list of integers is now : ");
ListNode result = invert(head);

printLinked(result.link);

它没有打印,因为您使用的是原来的头部,现在是列表的尾部。

关于java - 打印反向链表时出现问题(java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19205213/

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