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 /** 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* reverseBetween(ListNode* head, int m, int n) { 12 int d=n-m; 13 if(head==NULL||head->next==NULL||d<=0) 14 return head; 15 16 ListNode* p=head,*bfp=p; 17 ListNode* q=head; 18 for(int i=0;i<m-1;i++){ 19 bfp=p; 20 p=p->next; 21 } 22 ListNode* revhead=p; 23 ListNode* bf=p,*bh=NULL; 24 p=p->next; 25 d--; 26 while(p->next!=NULL&&d!=0){ 27 d--; 28 bh=p->next; 29 p->next=bf; 30 bf=p; 31 p=bh; 32 33 } 34 bh=p->next; 35 p->next=bf; 36 bfp->next=p; 37 revhead->next=bh; 38 if(m!=1) 39 return head; 40 else return p; 41 } 42 };
时间: 2024-12-09 19:32:33