原题网址:https://www.lintcode.com/zh-cn/old/problem/reverse-linked-list-ii/#
36. 翻转链表 II
翻转链表中第m个节点到第n个节点的部分
注意事项
m,n满足1 ≤ m ≤ n ≤ 链表长度
您在真实的面试中是否遇到过这个题?
Yes
样例
给出链表1->2->3->4->5->null, m = 2 和n = 4,返回1->4->3->2->5->null
挑战
在原地一次翻转完成
标签
思路:通过while循环找到链表的第m个结点与第n个结点。然后通过三根指针翻转m~n中间的节点,原地翻转的思路可以参考翻转链表一题:http://www.cnblogs.com/Tang-tangt/p/8709167.html ,区别是后继结点初值不为NULL而是等于原链表m+1个结点。
翻转完成后判断原链表第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; } };