顺序建立链表
import java.util.Scanner; class Node{ int data; Node next; Node(){ this.data = -1; this.next = null; } Node(int data){ this.data = data; this.next = null; } boolean hasNext() { return this.next == null ? false : true; } } public class Main{ public static void main(String []args) { Scanner cin = new Scanner(System.in); Node head = null; Node tail = null; tail = head; int n , i , v; n = cin.nextInt(); for(i = 0;i<n;i++) { v = cin.nextInt(); Node p = new Node(v); if(head==null) { head = p; tail = p; } else { tail.next = p; tail = p; } } tail = head; while(tail.hasNext()) { System.out.print(tail.data + " "); tail = tail.next; } System.out.println(tail.data); cin.close(); } }
逆序建立链表
import java.util.Scanner; class Node{ int data; Node next; Node(){ this.data = -1; this.next = null; } Node(int data){ this.data = data; this.next = null; } boolean hasNext() { return this.next == null ? false : true; } } public class Main{ public static void main(String []args) { Scanner cin = new Scanner(System.in); Node head = null; Node tail = null; tail = head; int n , i , v; n = cin.nextInt(); for(i = 0;i<n;i++) { v = cin.nextInt(); Node p = new Node(v); if(head==null) { head = p; tail = p; } else { p.next = head; head = p; } } tail = head; while(tail.hasNext()) { System.out.print(tail.data + " "); tail = tail.next; } System.out.println(tail.data); cin.close(); } }