0%

Leetcode206-reverseLinkedList

Description

Reverse a singly linked list.

Example

1
2
Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL

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

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode Recursion(ListNode head, ListNode newHead){
if (head == null){
return newHead;
}
ListNode next = head.next;
head.next = newHead;
return Recursion(next, head);
}

public ListNode reverseList(ListNode head) {
// ListNode newHead = null;
// while (head != null){
// ListNode next = head.next;
// head.next = newHead;
// newHead = head;
// head = next;
// }
// return newHead;
return Recursion(head, null);
}
}