92.leetcode Reverse Linked List II(medium)[链表逆序]

来源:互联网 发布:sai绘画软件下载 编辑:程序博客网 时间:2024/05/16 10:30

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->NULLm = 2 and n = 4,

return 1->4->3->2->5->NULL.

Note:
Given mn 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;    }


0 0
原创粉丝点击