Monday, May 4, 2015

206 Reverse Linked List I

来源:Leetcode

原帖:https://leetcode.com/problems/reverse-linked-list/

题目:
Given a linear time non-recursive function that reverses a singly linked list. The function should use no more than constant storage beyond that needed for the list itself.

代码:
 struct ListNode {  
     int val;  
     ListNode* next;  
     ListNode(int v) : val(v), next(NULL) {}  
 };  
   
 //Recursion  
 ListNode* reverse_linked_list(ListNode* head) {  
     if (!head || !head->next) {  
         return head;  
     }  
     ListNode* new_head = reverse_linked_list(head->next);  
     head->next->next = head;  
     head->next = NULL;  
     return new_head;  
 }  
   
 //Iteration  
 ListNode* reverse_linked_list(ListNode* head) {  
     if (!head) return NULL;  
     ListNode* newhead = head;  
     while (head->next) {  
         ListNode* n = head->next;  
         head->next = n->next;  
         n->next = newhead;  
         newhead = n;  
     }  
     return newhead;  
 }  
   

No comments:

Post a Comment