您的位置:首页 > 编程语言 > C语言/C++

LeetCode92-反转链表 II(C++实现)

2019-05-26 21:41 435 查看

1.题目描述

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

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

示例:

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

 

2.代码实现

[code]/**
* 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;

if(m == 1)
{
int cnt = 0;
ListNode* myhead = new ListNode(-1);
myhead->next = head;
ListNode* cur = head;
while(cnt < (n - m) && cur->next)
{
ListNode *t = cur->next;
cur->next = t->next;
t->next = myhead->next;
myhead->next = t;
cnt++;
}
head = myhead->next;
delete myhead;
}
else
{
ListNode* pre = head;
for(int i = 1; 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 head;
}
};

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: