Reverse a singly linked list.
Example:
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?
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 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 | /** * 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 || !(head->next)) return head; ListNode* H = new ListNode(0); H->next = head; ListNode* p = head->next; head->next = NULL; while(p) { ListNode* q = p->next; p->next = H->next; H->next = p; p = q; } return H->next; } }; //C++: method1 14ms /** * 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 *H = new ListNode(0); while(head){ ListNode *first = H->next; H->next = head; head = head->next; H->next->next = first; } return H->next; } }; ]]></script> <script class="brush: js" type="syntaxhighlighter"><![CDATA[ //C++: method2 12ms /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: void helper(ListNode* head, ListNode* H){ if(!head) return; ListNode* first = H->next; H->next = head; ListNode* next = head->next; H->next->next = first; helper(next, H); } ListNode* reverseList(ListNode* head) { ListNode *H = new ListNode(0); helper(head, H); return H->next; } }; ]]></script> <script class="brush: js" type="syntaxhighlighter"><![CDATA[ //C++: method3 8ms /** * 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 || !head->next) return head; ListNode* newHead = reverseList(head->next); head->next->next = head; head->next = NULL; return newHead; } }; |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | /** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode() {} * ListNode(int val) { this.val = val; } * ListNode(int val, ListNode next) { this.val = val; this.next = next; } * } */ class Solution { public ListNode reverseList(ListNode head) { ListNode H = new ListNode(); ListNode p = head; while(p!=null){ ListNode h = H.next; ListNode next = p.next; p.next = h; H.next = p; p = next; } return H.next; } } |
No comments:
Post a Comment