标签:nod def col node else turn 循环 nbsp note
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->NULL
, m = 2 and n = 4,
return 1->4->3->2->5->NULL
.
Note:
Given m, n satisfy the following condition:
1 ≤ m ≤ n ≤ length of list.
此题在上题的基础上加了位置要求,只翻转指定区域的链表。由于链表头节点不确定,使用dummy节点。。
/** * 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) { if (head == nullptr || m > n) return head; ListNode* dummy = new ListNode(0); dummy->next = head; ListNode* node = dummy; for (int i = 1; i != m; i++) { if (node == nullptr) return node; else node = node->next; } ListNode* premNode = node; ListNode* mNode = node->next; ListNode* nNode = mNode; ListNode* postnNode = nNode->next; for (int i = m; i != n; i++) { ListNode* tmp = postnNode->next; postnNode->next = nNode; nNode = postnNode; postnNode = tmp; } premNode->next = nNode; mNode->next = postnNode; return dummy->next; } }; // 6 ms
[LeetCode] Reverse Linked List II
标签:nod def col node else turn 循环 nbsp note
原文地址:http://www.cnblogs.com/immjc/p/7779011.html