原题网址:https://www.lintcode.com/zh-cn/old/problem/reverse-linked-list-ii/#
36. 翻转链表 II
讨论区
样例
给出链表1->2->3->4->5->null, m = 2 和n = 4,返回1->4->3->2->5->null
标签
翻转完成后判断原链表第n-1个是否为空,若不为空要将翻转后的链表挂载到第n-1个节点后面,若为空直接返回翻转链表。
AC代码:
/**
* Definition of singly-linked-list:
* class ListNode {
* public:
* int val;
* ListNode *next;
* ListNode(int val) {
* this->val = val;
* this->next = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param head: ListNode head is the head of the linked list
* @param m: An integer
* @param n: An integer
* @return: The head of the reversed ListNode
*/
ListNode * reverseBetween(ListNode * head, int m, int n) {
// write your code here
if (head==NULL)
{
return head;
}
ListNode * leftNodes=NULL;
ListNode *rightNodes=head;
ListNode * cur=head;
int i=1,j=i,count=0;
while(i<m)//找到原链表第m个节点;
{
leftNodes=cur;
cur=cur->next;
i++;
}
while(j<n)//找到原链表第n个节点;
{
rightNodes=rightNodes->next;
j++;
}
rightNodes=rightNodes->next;
ListNode * rePre=cur;
ListNode *renexN=rightNodes;//翻转部分尾节点应挂载原链表右侧部分;
while(rePre!=rightNodes)//翻转m~n的节点;
{
rePre=cur->next;
cur->next=renexN;
renexN=cur;
cur=rePre;
}
//renexN为翻转部分头部,应挂载到原链表左侧部分;
if (leftNodes==NULL)
{
return renexN;
}
leftNodes->next=renexN;
return head;
}
};