链表实现单链表的逆序

Posted jiangyi-uestc

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了链表实现单链表的逆序相关的知识,希望对你有一定的参考价值。

 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 }

 

以上是关于链表实现单链表的逆序的主要内容,如果未能解决你的问题,请参考以下文章

单链表基本操作

算法与数据结构单链表的增删改查逆序打印与输出合并有序链表

栈和队列----将单链表的每K个节点之间逆序

(单链表)单链表的整体逆序和局部逆序

C++怎么利用递归实现单线链表的反向输出??

1.单链表的逆序(JavaScript版) 使用递归实现