导航
导航
文章目录
  1. 题目
  2. 翻译
    1. 非递归
    2. 递归

LeetCode-206.Reverse Linked List

题目

Reverse a singly linked list.

Hint:
A linked list can be reversed either iteratively or recursively. Could you implement both?

翻译

反转一个单链表。
提示:
单链表反转可以使用递归和非递归方法,你能都实现吗?

经典问题,没什么好讲解。

非递归

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 Solution {
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null)
return head;
ListNode left = head.next, right;
head.next = null;
while (left != null) {
right = left.next;
left.next = head;
head = left;
left = right;
}
return head;
}
}

递归

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null)
return head;
ListNode newHead = reverseList(head.next);
head.next.next = head;
head.next = null;
return newHead;
}
}