Reverse a singly linked list.
Hint:
A linked list can be reversed either iteratively or recursively. Could you implement both?
Solution
* Java
(Reverse-Linked-List.java) download
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 Solution {
public ListNode reverseList(ListNode head) {
return reverse(head,null);
}
public ListNode reverse(ListNode head, ListNode newhead){
if(head==null)
return newhead;
ListNode nextNode = head.next;
head.next = newhead;
return reverse(nextNode,head);
}
}
|
- Python
File /Users/minli/Desktop/Personal/sdytlm.github.io/source/downloads/code/LeetCode/Python/Reverse-Linked-List.py could not be found