Reverse a linked list from position m to n. Do it in one-pass.
Note: 1 ≤ m ≤ n ≤ length of list.
Example:
Input: 1->2->3->4->5->NULL, m = 2, n = 4
Output: 1->4->3->2->5->NULL
ListNode* reverseBetween(ListNode* head, int m, int n) {
if(head==NULL)
return NULL;
ListNode* dummy = new ListNode(0);
dummy->next=head;
ListNode* pre=dummy;
for(int i=0;i<m-1;i++){ //从0开始,所以是m-1
pre=pre->next;
}
ListNode* start=pre->next;
ListNode* then=start->next;
for(int i=0;i<n-m;i++){
start->next=then->next;
then->next=pre->next;
pre->next=then;
then=start->next;
}
return dummy->next;
}
};
方法:和反转链表1差不多,区别有以下:
1.设置了dummyhead,返回的时候直接返回dummy->next(头结点);即可
2.pre指针为m的前一个。
3.ListNode* dummy = new ListNode(0);
new的用法(manage dynamic storage):
case1:
int *x = new int; //开辟一个存放整数的存储空间,返回一个指向该存储空间的地址(即指针)
int *a = new int(100); //开辟一个存放整数的空间,并指定该整数的初值为100,返回一个指向该存储空间的地址
4.过程:
1 -> 2 -> 3 -> 4 -> 5 -> NULL
1 -> 3 -> 2 -> 4 -> 5 -> NULL
1 -> 4 -> 3 -> 2 -> 5 -> NULL