算法 Java Leetcode Golang

Reverse a singly linked list.

Question

Reverse a singly linked list.
See it on Leetcode

1
2
3
For example,
Assume that we have linked list 123 → Ø
We would like to change it to Ø ← 123

Hint

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

Solution in iteratively approach

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

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

Solution in recursively approach

  • java
  • cpp
  • go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/**
* 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 p = reverseList(head.next);
head.next.next = head;
head.next = null;
return p;
}
}