LeetCode206-反转链表

题目链接

英文链接:https://leetcode.com/problems/reverse-linked-list/

中文链接:https://leetcode-cn.com/problems/reverse-linked-list/

题目详述

反转一个单链表。

示例:

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

进阶:
你可以迭代或递归地反转链表。你能否用两种方法解决这道题?

题目详解

解决这种问题免不了对结点的 next 进行操作,最好的方式是先用纸笔画图模拟一下操作过程,再来写代码。

下面是迭代版本:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class LeetCode_00206 {

// 迭代版本
public ListNode reverseList(ListNode head) {
ListNode cur = head;
ListNode pre = null;
while (cur != null) {
ListNode next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
return pre;
}
}

下面是递归版本:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class LeetCode_00206 {

// 递归版本
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode newHead = reverseList(head.next);
// 在反转过程中,head 指向下一个结点的指针没有变化,故可以用 head.next获取到反转链表的尾结点
head.next.next = head;
head.next = null;
return newHead;
}
}