1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
|
public class List { Node head; public List(Node head) { this.head = head; } static class Node { int data; Node next; public Node() {} public Node(int data, Node next) { this.data = data; this.next = next; } } public void reverse() { if (null == head || null == head.next || null == head.next.next) return; Node pre = null, cur = this.head.next, nex = cur.next; while (null != nex) { cur.next = pre; pre = cur; cur = nex; nex = nex.next; } cur.next = pre; this.head.next = cur; } public void traverse() { if (null == head.next) return; Node cur = head.next; while (null != cur) { System.out.println(cur.data); cur = cur.next; } System.out.println("traverse end \n"); } public static void main(String[] args) { Node n7 = new Node(7, null); Node n6 = new Node(6, n7); Node n5 = new Node(5, n6); Node n4 = new Node(4, n5); Node n3 = new Node(3, n4); Node n2 = new Node(2, n3); Node n1 = new Node(1, n2); Node head = new Node(0, n1); List list = new List(head); list.traverse(); list.reverse(); list.traverse(); } }
|