Question
Reverse a singly linked list.
click to show more hints.
Show Tags
Show Similar Problems
Solution 1
Analysis
recursive method
Code
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if head==None or head.next==None:
return head
tail = head.next
n = self.reverseList(tail)
head.next = None
tail.next = head
return n
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(head==NULL || head->next==NULL) return head;
ListNode* second = head->next;
ListNode* rest_head = reverseList(second);
second->next = head;
head->next = NULL;
return rest_head;
}
};
Solution2
Analysis
iterative method
Example:
input: 1->2->3->4->None
p l
1 2->3->4->None
p l
2->1 3->4->None
p l
3->2->1 4->None
p l
4->3->2->1 None
Code
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if head==None or head.next==None:
return head
p = head; # p is the head of reversed likedin list
l = head.next # l is the head of the rest likedin list
p.next = None
while(l):
t = l.next # after this, l is middle node between reversed list and the rest list
l.next = p
p = l
l = t
return p
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if( head==NULL || head->next==NULL) return head;
ListNode* p = head;
ListNode* l = head->next;
head->next = NULL;
while(l){
ListNode* t = l->next;
l->next = p;
p = l;
l = t;
}
return p;
}
};
When thinking it in iterative way, we need to get what intermediate state looks like. For this problem, several nodes are reversed with header pointer, and the rest nodes with the header pointer.
Actually, recursive method reversed linked list one by one from the ending node to the beginning node. Iterative method does it from the starting node.
Iterative method can’t reverse node from the ending node. It is easy to know that additional time O(n) will be cost to obtain the previous node of p.