92.leetcode Reverse Linked List II(medium)[链表逆序]
2016-08-24 16:30
309 查看
Reverse a linked list from position m to n. Do it in-place and in one-pass.
For example:
Given
return
Note:
Given m, n satisfy the following condition:
1 ≤ m ≤ n ≤ length of list.
首先找到需要翻转的部分链表放入stack里面,然后将stack里面的部分和外面未改动的部分连接起来,注意由于有可能翻转第一个节点,所以最好新生成一个头结点来连接。
ListNode* reverseBetween(ListNode* head, int m, int n) {
if(head == NULL) return head; //采用stack链表翻转的思想
ListNode* p = head;
int count = 1;
ListNode* bef = new ListNode(-1);
ListNode* temp = bef;
ListNode* aft = NULL;
stack<ListNode*> reverse;
while(p!= NULL)
{
cout<<count<<endl;
cout<<"fd:"<<p->val<<endl;
if(count <m)
{
bef->next = p;
bef = bef->next;
}
else if(count>=m &&count<=n)
{
//cout<<"f"<<endl;
reverse.push(p);
}
else if(count>n)
{
aft = p;
break;
}
p = p->next;
++count;
}
while(!reverse.empty())
{
bef->next = reverse.top();
bef = bef->next;
reverse.pop();
}
bef->next = aft;
printList(temp->next);
return temp->next;
}
For example:
Given
1->2->3->4->5->NULL, m = 2 and n = 4,
return
1->4->3->2->5->NULL.
Note:
Given m, n satisfy the following condition:
1 ≤ m ≤ n ≤ length of list.
首先找到需要翻转的部分链表放入stack里面,然后将stack里面的部分和外面未改动的部分连接起来,注意由于有可能翻转第一个节点,所以最好新生成一个头结点来连接。
ListNode* reverseBetween(ListNode* head, int m, int n) {
if(head == NULL) return head; //采用stack链表翻转的思想
ListNode* p = head;
int count = 1;
ListNode* bef = new ListNode(-1);
ListNode* temp = bef;
ListNode* aft = NULL;
stack<ListNode*> reverse;
while(p!= NULL)
{
cout<<count<<endl;
cout<<"fd:"<<p->val<<endl;
if(count <m)
{
bef->next = p;
bef = bef->next;
}
else if(count>=m &&count<=n)
{
//cout<<"f"<<endl;
reverse.push(p);
}
else if(count>n)
{
aft = p;
break;
}
p = p->next;
++count;
}
while(!reverse.empty())
{
bef->next = reverse.top();
bef = bef->next;
reverse.pop();
}
bef->next = aft;
printList(temp->next);
return temp->next;
}
相关文章推荐
- 链表逆序
- 逆序输出链表元素
- C语言笔试题(8)——链表逆序
- java单链表逆序用法代码示例
- 通过迭代(非递归)及递归将单链表逆序
- 链表逆序
- 2. Add Two Numbers 给定的两个链表是逆序排列的,相加后放在一个新的链表里边
- 链表的逆序,排序等
- 【面试题】剑指offer05--逆序打印链表
- 剑指offer 链表的逆序
- 逆序输出链表的元素
- 2117 数据结构实验之链表二:逆序建立链表
- 剑指offer 单链表逆序
- 数据结构实验之链表二:逆序建立链表
- 单向链表逆序
- 算法题:链表的递归逆序
- 将一个单向链表逆序
- 【数据结构】递归实现链表逆序
- 单链表操作大全(图解逆序)
- 剑指Offer14 逆序链表