/**
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
206. 反转链表
问题描述
问题思路
- 利用外部空间:将所给链表存到 ArryList 里面或者是新的链表里面,然后再反转动态数组就可以了。
- 快慢指针:
- 递归解法:
代码实现
递归实现
// 避免陷入死循环
if (head == null || head.next == null) return head;
ListNode newHead = reverseList(head.next); //此处递归,找到最后一个节点了
head.next.next = head; //重新指定节点指向(有两个next,注意少写)
head.next = null; //将最初的节点指向空
return newHead; //返回新的“倒置”头节点
快慢指针
class Solution {
public ListNode reverseList(ListNode head) {
// 避免陷入死循环
if (head == null || head.next == null) return head;
ListNode newHead = null;
while (head != null){
ListNode tmp = head.next;
head.next = newHead;
newHead = head;
head = tmp;
}
return newHead;
}
}
##