gpt4 book ai didi

java - 如何使用java在链表中插入节点?

转载 作者:行者123 更新时间:2023-11-30 02:28:59 26 4
gpt4 key购买 nike

我正在尝试这个方法,但我无法找出问题所在。我认为 insert() 方法存在一些问题,因为我没有使用递归,但我无法准确指出它。提前致谢。

import java.io.*;
import java.util.*;

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

class Solution {
public static Node insert(Node head,int data) {
//Some problem in this method
if(head==null)
return new Node(data);
else{
Node nxt = head;
while(nxt!=null)
nxt = nxt.next;
nxt = new Node(data);
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();
}
}

最佳答案

尝试使用以下代码。

class Nodes {
int data;
Nodes next;

Nodes(int data) {
this.data = data;
}
}


/**
* Insert in linkedList
*
* @author asharda
*
*/
public class LinkedListSum {


public Nodes insert(Nodes node, int data) {
Nodes temp;
if (node == null) {
node = new Nodes(data);
return node;
} else {
temp = node;
while (temp.next != null) {
temp = temp.next;
}
temp.next = new Nodes(data);
return node;
}
}// end of insert

/**
* Display LinkedList
*
* @param root
*/
public void display(Nodes root) {
while (root != null) {
System.out.println(root.data);
root = root.next;
}
}

/**
* @param args
*/
public static void main(String[] args) {
LinkedListSum sum = new LinkedListSum();
Nodes head = null;
head = sum.insert(head, 3);
head = sum.insert(head, 1);
head = sum.insert(head, 5);
sum.display(head);
}

}

关于java - 如何使用java在链表中插入节点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44733340/

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