题目大意:反转链表中的第m到第n个结点
分析:链表操作。
代码:
/**
* 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 = new ListNode(0);
dummy->next = head;
ListNode* pre = dummy;
for(int i = 1;i < m;i++){
pre = pre->next; //pre指向第m个结点的前一个
}
head = pre->next;
for(int i = m;i < n;i++){
ListNode* p = pre->next;
pre->next = head->next;
head->next = pre->next->next;
pre->next->next = p;
}
return dummy->next;
}
};