题目描述(Medium)
Reverse a linked list from position m to n. Do it in one-pass.
Note: 1 ≤ m ≤ n ≤ length of list.
题目链接
https://leetcode.com/problems/reverse-linked-list-ii/description/
Example 1:
Input: 1->2->3->4->5->NULL, m = 2, n = 4
Output: 1->4->3->2->5->NULL
算法分析
头插法。
提交代码:
ListNode* reverseBetween(ListNode* head, int m, int n) {
ListNode* dummy = new ListNode(-1);
dummy->next = head;
ListNode* prev = dummy;
for (int i = 0; i < m - 1; ++i)
prev = prev->next;
ListNode* head2 = prev;
prev = head2->next;
ListNode* curr = prev->next;
for (int i = m; i < n; ++i)
{
// 头插法
prev->next = curr->next;
curr->next = head2->next;
head2->next = curr;
curr = prev->next;
}
return dummy->next;
}
测试代码:
// ====================测试代码====================
void Test(const char* testName, ListNode* head, int m, int n, ListNode* expected)
{
if (testName != nullptr)
printf("%s begins: \n", testName);
Solution s;
ListNode* result = s.reverseBetween(head, m, n);
while (result && expected)
{
if (result->val != expected->val)
{
printf("failed\n");
return;
}
result = result->next;
expected = expected->next;
}
if(result || expected)
printf("failed\n");
else
printf("passed\n");
//if (result == expected)
// printf("passed\n");
//else
// printf("failed\n");
}
int main(int argc, char* argv[])
{
ListNode* node1 = new ListNode(1);
ListNode* node2 = new ListNode(2);
ListNode* node3 = new ListNode(3);
ListNode* node4 = new ListNode(4);
ListNode* node5 = new ListNode(5);
ConnectListNodes(node1, node2);
ConnectListNodes(node2, node3);
ConnectListNodes(node3, node4);
ConnectListNodes(node4, node5);
ListNode* node6 = new ListNode(1);
ListNode* node7 = new ListNode(4);
ListNode* node8 = new ListNode(3);
ListNode* node9 = new ListNode(2);
ListNode* node10 = new ListNode(5);
ConnectListNodes(node6, node7);
ConnectListNodes(node7, node8);
ConnectListNodes(node8, node9);
ConnectListNodes(node9, node10);
Test("Test1", node1, 2, 4, node6);
return 0;
}