92. Reverse Linked List II

来源:互联网 发布:淘宝 自带 库存管理 编辑:程序博客网 时间:2024/05/22 07:50

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->NULLm = 2 and n = 4,

return 1->4->3->2->5->NULL.

Note:
Given mn satisfy the following condition:

1 ≤ m ≤ n ≤ length of list.

 

剑指offer:反转链表


头插法

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public:    ListNode* reverseBetween(ListNode* head, int m, int n) {ListNode dummy(0);dummy.next=head;        ListNode* pre=&dummy;int cnt=m;while(cnt>1){pre=head;head=head->next;cnt--;}ListNode* tail=head;ListNode* front=head;for(int i=m+1;i<=n;i++){head=tail->next;ListNode* next=head->next;tail->next=next;head->next=front;pre->next=head;front=head;}return dummy.next;    }};


0 0