[LeetCode]Reverse Linked List II
题目描述:(链接)
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.
解题思路:
头插法
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode(int x) : val(x), next(NULL) {} 7 * }; 8 */ 9 class Solution { 10 public: 11 ListNode* reverseBetween(ListNode* head, int m, int n) { 12 ListNode dummy(-1); 13 dummy.next = head; 14 ListNode *prev = &dummy; 15 for (int i = 0; i < m - 1; ++i) { 16 prev = prev->next; 17 } 18 19 ListNode *head2 = prev; 20 prev = head2->next; 21 ListNode *current = prev->next; 22 for (int i = m; i < n; ++i) { 23 prev->next = current->next; 24 current->next = head2->next; 25 head2->next = current; 26 current = prev->next; 27 } 28 29 return dummy.next; 30 } 31 };
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步