单链表询问用户节点的大小,并在java中的每个节点中放置一个元素
我只能将其输出到
12345
54321
如何要求用户输入节点的大小 并根据节点的大小放置元素
应该是这样的:
样本输出:
输入节点数:3
节点1的输入数据:5
节点2的输入数据:6
节点3的输入数据:7
列表中输入的数据为:5 6 7
相反的列表是:7 6 5
public class LinkedList
{
private Node head;
private Node current;
private static class Node
{
private int data;
private Node next;
public Node(int data)
{
this.data = data;
this.next = null;
}
}
public void display()
{
Node current = head;
while (current != null)
{
System.out.print(current.data + " ");
current = current.next;
}
System.out.println("null");
}
public void reverse()
{
Node next = head;
Node previous = null;
current = null;
while(next != null)
{
current = next;
next = next.next;
current.next = previous;
previous = current;
head = current;
}
}
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
LinkedList list = new LinkedList();
System.out.print("Eneter number of nodes: ");
int size = sc.nextInt();
//this is the part where I need a user input
//for node size and put elements in each nodes
list.head = new Node(1);
Node second = new Node(2);
Node third = new Node(3);
Node fourth = new Node(4);
Node fifth = new Node(5);
list.head.next = second;
second.next = third;
third.next = fourth;
fourth.next = fifth;
list.display();
list.reverse();
list.display();
}
}
# 1 楼答案
您可以创建一个insert方法来轻松处理插入