结点类

  1. public class Node
  2. {
  3. //数据域
  4. public Integer data;
  5. //指针域
  6. public Node next;
  7. public Node(){
  8. }
  9. public Node(int data)
  10. {
  11. this.data = data;
  12. }
  13. public Node(int data, Node next)
  14. {
  15. this.data = data;
  16. this.next = next;
  17. }
  18. }

链表实现

  1. import java.util.Scanner;
  2. public class linkedList
  3. {
  4. static int N;
  5. public static void main(String[] args)
  6. {
  7. Scanner sc = new Scanner(System.in);
  8. N = sc.nextInt();
  9. //头结点
  10. Node head = new Node();
  11. //临时结点,用于指向链表当前最后一个结点
  12. Node temp = head;
  13. for(int i=0; i<N; i++)
  14. {
  15. Node p = new Node(sc.nextInt());
  16. if(head.next == null)
  17. head.next = p; //如果这是第一个创建的结点,则将头指针指向这个结点
  18. else
  19. temp.next = p; //如果不是第一个创建的结点,则将上一个结点的后继指针指向当前结点
  20. temp = p; //指针temp也指向当前结点
  21. }
  22. sc.close();
  23. //输出链表中所有数
  24. temp = head;
  25. while(temp.next != null)
  26. {
  27. temp = temp.next;
  28. System.out.print(temp.data + " ");
  29. }
  30. }
  31. }

Input & Output

[Input Example]

  1. 9
  2. 2 3 5 8 9 10 18 26 32

[Output Example]

  1. 2 3 5 8 9 10 18 26 32