看一遍就理解，图解单链表反转

18,292 阅读3分钟

前言

leetcode的反转链表原题&答案

``````输入: 1->2->3->4->5->NULL

``````

``````public ListNode reverseList(ListNode head) {
ListNode prev = null;
while (curr != null) {
ListNode nextTemp = curr.next;
curr.next = prev;
prev = curr;
curr = nextTemp;
}
return prev;
}
``````

图解链表反转代码的实现

``````public ListNode reverseList(ListNode head) {  //1
ListNode prev = null;   // 2
ListNode curr = head;   // 3
while (curr != null) {   //4
ListNode nextTemp = curr.next; //5
curr.next = prev;  // 6
prev = curr;  //7
curr = nextTemp; //8
}
return prev;  //9
}
``````

第一行代码图解

``````public ListNode reverseList(ListNode head) {  //1
``````

第二行代码图解

``````ListNode prev = null;   // 2
``````

第三行代码图解

``````ListNode curr = head;
``````

循环部分代码图解

`````` while (curr != null) {   //4
ListNode nextTemp = curr.next; //5
curr.next = prev;  // 6
prev = curr;  //7
curr = nextTemp; //8
}
``````

``````ListNode nextTemp = curr.next; //5
``````

``````curr.next = prev;  // 6
``````

`````` prev = curr;  //7
``````

``````curr = nextTemp; //8
``````

5-8行代码又执行一遍，依次可得图：

``````        ListNode nextTemp = curr.next; //5
curr.next = prev;  // 6
prev = curr;  //7
curr = nextTemp; //8
``````

``````        ListNode nextTemp = curr.next; //5
curr.next = prev;  // 6
prev = curr;  //7
curr = nextTemp; //8
``````

`````` return prev;  //9
``````

个人公众号

• 如果你是个爱学习的好孩子，可以关注我公众号，一起学习讨论。
• 如果你觉得本文有哪些不正确的地方，可以评论，也可以关注我公众号，私聊我，大家一起学习进步哈。