LeetCode92(反转链表II)

菜鸟成长逆袭之旅,爱好撸铁和撸代码,有强制的约束力,希望通过自己的努力做一个高品质人
Work together and make progress together

反转链表II

反转从位置 m 到 n 的链表。请使用一趟扫描完成反转。

说明:
1 ≤ m ≤ n ≤ 链表长度。

示例:

输入: 1->2->3->4->5->NULL, m = 2, n = 4
输出: 1->4->3->2->5->NULL

/**
 * 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(-1),*pre = dummy;
		dummy->next = head;
		for (int i = 0;i < m-1; ++i) pre = pre->next;
		ListNode *cur = pre->next;
		for (int i = m;  i<n ;++i){
			ListNode *t = cur->next;
			cur->next = t->next;
			t->next = pre->next;
			pre->next = t;		
		}		
		return dummy->next;
    }
};
上一篇:算法:删除链表中重复的元素||


下一篇:leetcode_数据解构_链表_19_删除链表的倒数第N个结点(哑结点&&快慢指针法)