File tree Expand file tree Collapse file tree 2 files changed +89
-0
lines changed
link_list/src/main/java/com/cpucode/linked/list Expand file tree Collapse file tree 2 files changed +89
-0
lines changed Original file line number Diff line number Diff line change 2424- [x] [ SingleLinkedList__ 单链表] ( link_list/src/main/java/com/cpucode/linked/list/SingleLinkedList.java )
2525- [x] [ DoubleLinkedList__ 双链表] ( link_list/src/main/java/com/cpucode/linked/list/DoubleLinkedList.java )
2626- [ ] [ Josephu__ 约瑟夫] ( link_list/src/main/java/com/cpucode/linked/list/Josephu.java )
27+ - [x] [ Reverse__ 链表的逆序] ( link_list/src/main/java/com/cpucode/linked/list/Reverse.java )
2728
2829- [ 返回目录] ( #文件目录 )
2930
Original file line number Diff line number Diff line change 1+ package com .cpucode .linked .list ;
2+
3+ /**
4+ * @author : cpucode
5+ * @date : 2021/5/7
6+ * @time : 23:49
7+ * @github : https://github.com/CPU-Code
8+ * @csdn : https://blog.csdn.net/qq_44226094
9+ */
10+ public class Reverse {
11+ public static void main (String [] args ) {
12+ // 链表头结点
13+ LNode head = new LNode ();
14+ head .next = null ;
15+ LNode tmp = null ;
16+ LNode cur = head ;
17+
18+ // 构造单链表
19+ for (int i = 0 ; i < 8 ; i ++) {
20+ tmp = new LNode ();
21+ tmp .data = i ;
22+ tmp .next = null ;
23+ cur .next = tmp ;
24+ cur = tmp ;
25+ }
26+
27+ System .out .print ("逆序前: " );
28+ for (cur = head .next ; cur != null ; cur = cur .next ){
29+ System .out .print (cur .data + " " );
30+ }
31+
32+ ReverseTest (head );
33+
34+ System .out .print ("\n 逆序后: " );
35+ for (cur = head .next ; cur != null ; cur = cur .next ){
36+ System .out .print (cur .data + " " );
37+ }
38+ }
39+
40+ /**
41+ * 方法功能:对单链表进行逆序输入参数: head:链表头结点
42+ * @param head
43+ */
44+ public static void ReverseTest (LNode head ){
45+ // 判断链表是否为空
46+ if (head == null || head .next == null ){
47+ return ;
48+ }
49+
50+ // 前驱结点
51+ LNode pre = null ;
52+ // 当前结点
53+ LNode cur = null ;
54+ // 后继结点
55+ LNode next = null ;
56+
57+ // 把链表首结点变为尾结点
58+ cur = head .next ;
59+ next = cur .next ;
60+ cur .next = null ;
61+ pre = cur ;
62+ cur = next ;
63+
64+ // 使当前遍历到的结点 cur 指向其前驱结点
65+ while (cur .next != null ){
66+ next = cur .next ;
67+ cur .next = pre ;
68+ pre = cur ;
69+ cur = next ;
70+ }
71+ // 结点最后一个结点指向倒数第二个结点
72+ cur .next = pre ;
73+ // 链表的头结点指向原来链表的尾结点
74+ head .next = cur ;
75+ }
76+ }
77+
78+ class LNode
79+ {
80+ /**
81+ * 数据域
82+ */
83+ int data ;
84+ /**
85+ * 下一个结点的引用
86+ */
87+ LNode next ;
88+ }
You can’t perform that action at this time.
0 commit comments