翻转链表 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;
}
};
翻转链表中第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;
}
};
相关文章推荐
- lintcode,翻转链表 II
- 【LintCode】翻转链表 II
- [Lintcode]Reverse Linked List II 翻转链表 II
- [lintcode]36. 翻转链表 II
- lintcode 中等题: reverse linked list II 翻转链表II
- LintCode-----36.翻转链表 II
- 翻转链表 II
- 翻转链表II
- lintcode-221-链表求和 II
- LintCode_035_翻转链表
- lintcode-删除排序链表中的重复数字II-113
- Lintcode 35.翻转链表
- *[Lintcode]带环链表 II
- LintCode-[中等] 221. 链表求和 II
- lintcode 35. 翻转链表
- lintcode(221)链表求和 II
- LintCode_035_翻转链表
- Reverse Linked List II -- 翻转部分链表
- LintCode:翻转链表
- LintCode_103_带环链表 II