Reverse Linked List
Reverse a singly linked list.Analysis:
Classic problem. There are multiple algorithms to reverse the linked list. Here in this post I just describe the very basics. Some advanced algorithms can be found in other problems in my blog.
To illustrate the process, say we have the linked list:
1->2->3->4->5->null
head
In order to reverse it, we define a new pointer:
newhead->null
Iterate the original list, each time insert the node to the start of the new linked list:
1. newhead->1->null
2. newhead->2->1->null
...
5 newhead->5->4->3->2->1->null
Then just return newhead->next.
Code(C++):
/**
* 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) {
ListNode * newhead = new ListNode(0);
while (head){
ListNode * tmp = newhead->next;
newhead->next = head;
head = head->next;
newhead->next->next = tmp;
}
return newhead->next;
}
};
Code(Python):
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @param {ListNode} head
# @return {ListNode}
def reverseList(self, head):
newhead = ListNode(0)
while head:
tmp = newhead.next
newhead.next = head
head = head.next
newhead.next.next = tmp
return newhead.next
No comments:
Post a Comment