【链表】实现单链表的逆序

 1 public class Main {
 2 
 3     // 就地逆序法
 4     public Node reverse(Node head) {
 5         // no need to reverse
 6         if (head == null || head.next == null || head.next.next == null) {
 7             return head;
 8         }
 9 
10         // pointer
11         Node pre = head;
12         Node cur = head.next;
13         Node nex = head.next.next;
14 
15         while (nex != null) {
16             if (cur == head.next)  // the first node's next node is null
17             {
18                 cur.next = null;
19             } else {
20                 cur.next = pre;
21             }
22 
23             pre = cur;
24             cur = nex;
25             nex = nex.next;
26         }
27 
28         cur.next = pre;
29         head.next = cur;
30 
31         return head;
32     }
33 
34     // 插入法
35     public Node reverse2(Node head) {
36         if (head == null || head.next == null) {
37             return head;
38         }
39 
40         Node p1 = head.next;
41 
42         Node p = null;
43 
44         while (p1.next != null) {
45             p = p1.next;
46             p1.next = p.next;
47             p.next = head.next;
48             head.next = p;
49         }
50 
51         return head;
52     }
53 
54     public Node createListNodes() {
55         Node node7 = new Node(7, null);
56         Node node6 = new Node(6, node7);
57         Node node5 = new Node(5, node6);
58         Node node4 = new Node(4, node5);
59         Node node3 = new Node(3, node4);
60         Node node2 = new Node(2, node3);
61         Node node1 = new Node(1, node2);
62         Node head = new Node(0, node1); // head pointer
63 
64         return head;
65     }
66 
67     public static void main(String[] args) {
68         Main main = new Main();
69         Node node = main.reverse(main.createListNodes());
70 
71         if (node == null) {
72             System.out.println("head is null");
73             return;
74         }
75 
76         while (node.next != null) {
77             System.out.println(node.next.data);
78             node = node.next;
79         }
80 
81         Node node2 = main.reverse2(main.createListNodes());
82 
83         if (node2 == null) {
84             System.out.println("head is null");
85             return;
86         }
87 
88         while (node2.next != null) {
89             System.out.println(node2.next.data);
90             node2 = node2.next;
91         }
92     }
93 
94 }

 

posted @ 2018-12-01 22:22  Mr.van_Gogh  阅读(3272)  评论(0编辑  收藏  举报