1 /**
2 * @author 林夕
3 * 反转单链表的算法
4 */
5
6
7 //结点类
8 class Node{
9 //变量
10 private int record;
11 //下个结点
12 private Node nextNode;
13 //构造函数
14 public Node(int record){
15 this.record = record;
16 }
17
18 public int getRecord(){
19 return record;
20 }
21 public void setRecord(int record){
22 this.record = record;
23 }
24
25 public Node getNextNode(){
26 return nextNode;
27 }
28 public void setNextNode(Node nextNode){
29 this.nextNode = nextNode;
30 }
31 }
32
33
34 public class Solution {
35
36 /**
37 * 递归,在反转当前结点之前先反转后续结点
38 * 递归函数的中的return语句:
39 * return含义--->从被调函数返回到主调函数继续执行
40 */
41 public static Node reverse1(Node head){
42 //链表为空或者本结点为末尾结点时
43 if(head == null || head.getNextNode() == null){
44 return head;
45 }
46 Node reverseHead = reverse1(head.getNextNode());
47 //获取先前的下一个结点,让该结点指向自身
48 head.getNextNode().setNextNode(head);
49 //破坏以前自己指向的下一个结点
50 head.setNextNode(null);
51 return reverseHead;
52 }
53
54 public static Node reverse2(Node head) {
55 if(null == head){
56 return head;
57 }
58 Node pre = head;
59 Node cur = head.getNextNode();
60 Node next;
61
62 while(cur != null){
63 //断之前找到原始的下一个结点
64 next = cur.getNextNode();
65 //逆序连接
66 cur.setNextNode(pre);
67 //两个结点同时滑动
68 pre = cur;
69 cur = next;
70 }
71
72 //将原链表的头结点的下一个结点置为null,再将反转后的头结点赋给head
73 head.setNextNode(null);
74 head = pre;
75 return head;
76 }
77
78 public static void main(String[] args){
79 Node head = new Node(0);
80 Node tmp = null;
81 Node cur = null;
82 //初始化一个大小为10的单链表
83 for(int i = 1; i < 10; i++){
84 tmp = new Node(i);
85 if(i == 1){
86 head.setNextNode(tmp);
87 } else{
88 cur.setNextNode(tmp);
89 }
90 cur = tmp;
91 }
92
93 Node h = head;
94 while (h != null){
95 System.out.print(h.getRecord()+" ");
96 h = h.getNextNode();
97 }
98
99 head = reverse2(head);
100 System.out.println("\n反转后的链表如下:");
101 while (head != null){
102 System.out.print(head.getRecord()+" ");
103 head = head.getNextNode();
104 }
105 }
106
107
108 }