Reverse a singly linked list.
click to show more hints.
Hint:
A linked list can be reversed either iteratively or recursively. Could you implement both?
1 class Solution { 2 public: 3 ListNode* reverseList(ListNode* head) { 4 if(head==NULL||head->next==NULL) return head; 5 6 ListNode *p=head->next; 7 ListNode *newhead=reverseList(head->next); 8 head->next=NULL; 9 p->next=head; 10 return newhead; 11 12 } 13 };
II:
Reverse a linked list from position m to n. Do it in-place and in one-pass.
For example:
Given 1->2->3->4->5->NULL, m = 2 and n = 4,
return 1->4->3->2->5->NULL.
Note:
Given m, n satisfy the following condition:
1 ≤ m ≤ n ≤ length of list.
1 class Solution { 2 public: 3 ListNode* reverseBetween(ListNode* head, int m, int n) { 4 if(head==NULL||m<0||n<0) return head; 5 if(head->next==NULL||m==n) return head; 6 7 ListNode *p=head; 8 int i=1; 9 10 while(i<m) 11 { 12 p=p->next; 13 i++; 14 } 15 16 for(int j=m;j<n;j++) 17 { 18 ListNode *q=p; 19 for(int k=j;k<n;k++) 20 { 21 q=q->next; 22 } 23 swap(p->val,q->val); 24 25 n--; 26 p=p->next; 27 } 28 29 return head; 30 31 } 32 };