Reverse a singly linked list.
Hint:A linked list can be reversed either iteratively or recursively. Could you implement both?
Solution 1:iteration
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode(int x) : val(x), next(NULL) {} 7 * }; 8 */ 9 class Solution { 10 public: 11 ListNode* reverseList(ListNode* head) { //runtime:8ms 12 ListNode *p1,*p2,*p3; 13 if(head==NULL||head->next==NULL)return head; 14 p1=head,p2=p1->next; 15 while(p2){ 16 p3=p2->next; 17 p2->next=p1; 18 p1=p2; 19 p2=p3; 20 } 21 head->next=NULL; 22 head=p1; 23 return head; 24 } 25 };
Solution 2:recursion
1 class Solution { 2 public: 3 ListNode* reverseList(ListNode* head) { //runtime:8ms 4 if(head==NULL||head->next==NULL)return head; 5 6 ListNode* p = head->next; 7 ListNode* n = reverseList(p); 8 9 head->next = NULL; 10 p->next = head; 11 return n; 12 } 13 };
时间: 2024-11-08 23:52:55