[英]Trouble printing reversed linked list (java)
基本上,我创建了一些方法来打印整数链接列表,从链接列表中删除重复项,以及反转链接列表。 一切正常...几乎出于某种原因,在列表反转后,我无法使我的printLinked()方法正常工作。 就目前而言,我刚刚创建了一个while循环来输出反向列表,以便至少可以确定该列表已反向。 不过,我需要使用printLinked()方法。 如果有人能帮助我或指出问题的正确方向,那么我将不胜感激。 谢谢。
import java.util.Scanner;
公共类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;
}
您需要通过您的invert方法返回列表的新标题:
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);
这不是打印,因为您使用的是原来的表头,现在是列表的尾部。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.