我创建了一个简单的节点类,以及一个带有插入方法、显示方法和Main的解决方案类。我试图插入4个数字到链表,并有它显示整个列表。我最多只能让它显示2个数字。问题很可能出现在我的插入方法中。我花了好几个小时想弄清楚问题出在哪里。我的代码有什么问题吗?
public static Node insert(Node head, int data)
{
Node newNode = new Node(data);
if (head == null)
{
head = newNode;
}
else
{
while (head.next != null)
{
head = head.next;
}
head.next = newNode;
}
return head;
}
public static void display(Node head)
{
Node start = head;
while (start != null)
{
Console.Write(start.data + " ");
start = start.next;
}
}
static void Main(String[] args)
{
Node head = null;
int[] numbers = new int[]{2, 3, 4, 1};
for (int i = 0; i < numbers.Length; i++)
{
int data = numbers[i];
head = insert(head, data);
}
display(head);
Console.ReadLine();
}
class Node
{
public int data;
public Node next;
public Node(int d)
{
data = d;
next = null;
}
public Node() { }
}
是的,问题在insert
方法:
while (head.next != null)
{
// From now on you have the initial head got lost
head = head.next;
}
快速修改是将while
改为for
:
public static Node insert(Node head, int data) {
Node newNode = new Node(data);
if (head == null) {
head = newNode;
}
else {
// we loop on last, keeping head intact
for (Node last = head; ; last = last.next)
if (last.next == null) {
last.next = newNode;
break;
}
}
return head;
}
我们可以进一步简化:
public static Node insert(Node head, int data) {
Node newNode = new Node(data);
for (Node last = head; last != null; last = last.next)
if (last.next == null) {
last.next = newNode;
return head;
}
return newNode;
}