您的位置:首页 > 其它

翻转链表 II-LintCode

2018-02-07 16:50 429 查看
描述:

翻转链表中第m个节点到第n个节点的部分


 注意事项


m,n满足1 ≤ m ≤ n ≤ 链表长度

样例:

给出链表1->2->3->4->5->null, m = 2 和n = 4,返回1->4->3->2->5->null

思路:
1.先建立四个指针分别指向第m-1、m、n、n+1个节点的位置;

2.将第m到n个节点的链表拿出做翻转处理为新链表h;

3.按(0到m-1)+(翻转后的链表h)+(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
ListNode *f1=new ListNode(0);
ListNode *f2=new ListNode(0);
f1->next=head;
ListNode *p1,*p2,*pm,*pn,*temp,*p;
pm=f1;
pn=f1;

while(m>0)
{
p1=pm;
pm=pm->next;
m--;
}
p=pm;
while(n>0)
{
pn=pn->next;
n--;
}
p2=pn->next;
pn->next=NULL;

while(p!=NULL)
{
temp=p;
p=p->next;
temp->next=f2->next;
f2->next=temp;
}
p1->next=f2->next;
pm->next=p2;
return f1->next;

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