数据结构实验之链表一:顺序建立链表(java)

数据结构实验之链表一:顺序建立链表

Time Limit: 1000 ms  Memory Limit: 65536 KiB

Problem Description

输入N个整数,按照输入的顺序建立单链表存储,并遍历所建立的单链表,输出这些数据。

Input

第一行输入整数的个数N;
第二行依次输入每个整数。

Output

输出这组整数。

Sample Input

8
12 56 4 6 55 15 33 62

Sample Output

12 56 4 6 55 15 33 62
//package hello;
import java.util.Scanner;


class Node{
	int data;
	public Node next;
	
	public Node(int data) {
		this.data = data;
		this.next = null;
	}
	public Node create(int data) {
		return new Node(data);
	}
	public void addNode(Node head, Node node) {
		Node temp = head;
		while(temp.next != null) {
			temp = temp.next;
		}
		temp.next = node;
	}
	public void show(Node head) {
		Node temp = head;
		System.out.print(temp.data);
		temp = temp.next;
		while(temp.next != null) {
			System.out.print(" "+temp.data);
			temp = temp.next;
		}
		System.out.println(" "+temp.data);
	}
	
}
public class Main {
	public static void main(String[] args){
		Scanner cin = new Scanner(System.in);
		int n;
		int data;
		n = cin.nextInt();
		data = cin.nextInt();
		Node head = new Node(data);
		head = head.create(data);
		n--;
		while(n-- != 0) {
			data = cin.nextInt();
			Node temp = new Node(data);
			temp.addNode(head, temp);
		}
		head.show(head);
		cin.close();
	}
}

猜你喜欢

转载自blog.csdn.net/horizonhui/article/details/79698723
今日推荐