当前位置 : 主页 > 手机开发 > ROM >

Reverse Linked List II

来源:互联网 收集:自由互联 发布时间:2021-06-10
Reverse a linked list from position m to n . Do it in one-pass. Note:1 ≤ m ≤ n ≤ length of list. Example:Input: 1 - 2 - 3 - 4 - 5 -NULL, m = 2 , n = 4 Output: 1 - 4 - 3 - 2 - 5 -NULL code 思路:利用头插法建立链表的时候建
Reverse a linked list from position  m to  n. Do it in one-pass.

Note: 1 ≤ m ≤ n ≤ length of list.

Example:

Input: 1->2->3->4->5->NULL, m = 2, n = 4
Output: 1->4->3->2->5->NULL

code

  思路:利用头插法建立链表的时候建立的链表顺序与输入的顺序是相反的。

struct ListNode
{
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};
class Solution
{
public:
    ListNode* reverseBetween(ListNode* head, int m, int n)
    {
        if(n<=m)
            return head;

        ListNode newHead(-1);
        newHead.next=head;
        ListNode *pre=&newHead;

        int index=1;
        while(pre&&index<m)
        {
            pre=pre->next;
            ++index;
        }
        
        ListNode *cur=nullptr;
        if(pre->next)
            cur=pre->next;
        pre->next=nullptr;
        ListNode *next=nullptr;
        ListNode *tmp=cur;
        int count=n-m+1;
        while(cur&&count--)
        {
            next=cur->next;
            cur->next=pre->next;
            pre->next=cur;
            cur=next;
        }
        tmp->next=cur;
        return newHead.next;
    }
};
网友评论