您的位置:首页 > 其它

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