package test; public class ListNode{ int val; ListNode next; public ListNode(int x) { val = x; } public ListNode() {} public static void main(String[] args) { int n = 2; ListNode l1 = new ListNode(1); ListNode l2 = new ListNode(2); ListNode l3 = new ListNode(3); ListNode l4 = new ListNode(4); ListNode l5 = new ListNode(5); ListNode head = l1; l1.next = l2; l2.next = l3; l3.next = l4; l4.next = l5; while(head != null) { System.out.println(head.val); head = head.next; } ListNode h1 = new ListNode(); h1.next = head; //这里将 h1 指向了 head
ListNode first = h1; // 对 first 操作的时候, h1 和 head 也在改变。在内存三者共用同一块内存 first.next = l3; while(h1 != null) { System.out.println(h1.val); h1 = h1.next; } while(head != null) { System.out.println(head.val); head = head.next; } } }