使用java在链表中插入节点

问题描述 投票:0回答:4

我是java的初学者。我正在尝试使用java实现简单的链表结构。

我编写了以下代码,在链接列表的末尾插入节点。

 public static  Node insert(Node head,int data) {
    if(head == null)
    {
      Node temp = new Node(data);
        head = temp;
        return head;
    }
    else
    {
         Node temp = new Node(data);
    Node current = head;
    while(current != null)
    {
        current = current.next;
    }
    current = temp;
    return head;
    }
}

Node类定义如下

class Node {
int data;
Node next;
Node(int d) {
    data = d;
    next = null;
}
}

LinkListDemo类具有insert(),display()和main()方法,如下所示。

 class LinkListDemo
 {
 public static  Node insert(Node head,int data) {
    if(head == null)
    {
      Node temp = new Node(data);
        head = temp;
        return head;
    }
    else
    {
         Node temp = new Node(data);
    Node current = head;
    while(current != null)
    {
        current = current.next;
    }
    current = temp;
    return head;
    }
}
public static void display(Node head) {
    Node start = head;
    while(start != null) {
        System.out.print(start.data + " ");
        start = start.next;
    }
}

public static void main(String args[]) {
    Scanner sc = new Scanner(System.in);
    Node head = null;
    int N = sc.nextInt();

    while(N-- > 0) {
        int ele = sc.nextInt();
        head = insert(head,ele);
    }
    display(head);
    sc.close();
}
}

输入:4 2 3 4 1

我输入为4(要插入的节点数)2 3 4 1(对应的节点值)

我预计输出为2 3 4 1但输出仅为2。

请帮我纠正我的错误。提前致谢。

java data-structures
4个回答
1
投票

问题出在插入方法的else部分。你循环直到current变为null然后将新节点temp分配给它。分配对新节点(temp)的引用不会附加(或链接)到列表的末尾。

正确的方法是转到最后一个节点然后链接新节点,即使最后一个节点的下一个点指向新节点。

应该是这样的

while(current.next != null) {
    current = current.next;
}
current.next = temp;

0
投票

在你的insert()代码中,你应该有

while(current.next != null)
{
    current = current.next;
}

在您的代码中,您当前的变量将始终为null,从而导致您的节点实际上未被插入。此修复使您的当前变量成为列表中的最后一个节点,以便您可以设置最后一个节点指向新节点的指针。


0
投票

我正在使用以下代码插入节点

public void addFirst(int e) {
        if (head == null) {
            head = new LinkListNode(e);
            tail = head;
            size = 1;
        } else {
            LinkListNode nextNode = new LinkListNode(e);
            nextNode.setNext(head);
            head = nextNode;
            size++;
        }
    }

工作正常......


0
投票

只需改变一点代码

Node current = head;
while(current.next != null)
{
    current = current.next;
}
current.next= temp;

并回头

© www.soinside.com 2019 - 2024. All rights reserved.