标签:
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.
Linked List
这道题与上面的61题基本是相似的,只是要更加的注意一些特殊情况,比如m与n相等,m=1.或者n是最后一个
#include<iostream> using namespace std; struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; ListNode* reverseBetween(ListNode* head, int m, int n) { ListNode *ptr0=head; ListNode *ptr1=head; ListNode *ptr2=head; ListNode *ptr3=head; if(m==n) return head; if(m>1) { ptr1=ptr1->next; int a=m-2; while(a>0) { a--; ptr0=ptr0->next; ptr1=ptr1->next; } } ptr2=ptr1->next; int b=n-m-1; while(b>=0) { ptr3=ptr2->next; ptr2->next=ptr1; ptr1=ptr2; ptr2=ptr3; b--; } if(m==1) { if(ptr3==NULL) { ptr0->next=NULL; return ptr1; } else { ptr0->next=ptr3; return ptr1; } } else { if(ptr3==NULL) { ptr0->next->next=NULL; ptr0->next=ptr1; return head; } else { ptr0->next->next=ptr3; ptr0->next=ptr1; return head; } } } int main() { ListNode *root=(ListNode*)malloc(sizeof(ListNode)); root->val=1; root->next=(ListNode*)malloc(sizeof(ListNode)); root->next->val=2; root->next->next=(ListNode*)malloc(sizeof(ListNode)); root->next->next->val=3; root->next->next->next=NULL; reverseBetween(root,2,3); }
leetcode_92题——Reverse Linked List II(链表操作)
标签:
原文地址:http://www.cnblogs.com/yanliang12138/p/4548384.html