【LeetCode】92. Reverse Linked List II(C++)

地址:https://leetcode.com/problems/reverse-linked-list-ii/

题目:

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

理解:

需要把链表的一部分翻转。

实现:

添加了一个头结点来处理,其中
hh是头结点
pre是要反转的部分之前的结点
pppn指向当前处理的两个结点,pp在左,pn在右
pr是翻转后的尾节点
cnt是需要通过pppn处理的次数

class Solution {
public:
	ListNode* reverseBetween(ListNode* head, int m, int n) {
		ListNode* hh = new ListNode(0);
        hh->next=head;
		ListNode* pre = hh;
		for (int i = 0; i < m - 1; ++i)
			pre = pre->next;
		ListNode* pp = pre->next;
		ListNode* pr = pp;
		ListNode* pn = pp->next;
		int cnt = n - m;
		while (cnt) {
			ListNode* tmp = pn->next;
			pn->next = pp;
			pp = pn;
			pn = tmp;
            --cnt;
		}
		pre->next = pp;
		pr->next = pn;
		return hh->next;
	}
};

猜你喜欢

转载自blog.csdn.net/Ethan95/article/details/84998911
今日推荐