zoukankan      html  css  js  c++  java
  • leetcode[92]Reverse Linked List II

    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.

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
    ListNode *reverseBetween(ListNode *head, int m, int n) 
    {
        ListNode *newh=new ListNode(0);
        newh->next=head;
        ListNode *p=newh;
        ListNode *pre=newh, *left, *right, *after;
        int i=0;
        while (p&&i<m)
        {
            pre=p;
            p=p->next;
            left=p;
            right=left;
            i++;
        }
        p=p->next;
        after=p;
        for (i=m;i<n;i++)
        {
            p=p->next;
            right->next=after->next;
            pre->next=after;
            after->next=left;
            left=after;
            after=p;
        }
        return newh->next;
    }
    /*
    ListNode *reverseBetween(ListNode *head, int m, int n) 
    {
        ListNode *newh=new ListNode(0);
        newh->next=head;
        ListNode *p=newh->next;
        int i=1;
        vector<ListNode *> vec;
        while(p&&i<=n)
        {
            if(i>=m&&i<=n)
            {
                vec.push_back(p);
            }
            i++;
            p=p->next;
        }
        for (int j=0;j<(n-m+1)/2;j++)
        {
            int tmp=vec[j]->val;
            vec[j]->val=vec[(n-m)-j]->val;
            vec[(n-m)-j]->val=tmp;
        }
        return newh->next;
    }
    */
    };
  • 相关阅读:
    django 母版与继承
    django 模板系统
    及时从数据库中取得数据填放进Form表单的多选框中
    django 自带的验证功能
    django Form表单
    AJAX 操作
    django 中间件
    JVM-crash查看hs_err_pid.log日志
    java-log4j日志打印
    tomcat 闪退问题排查
  • 原文地址:https://www.cnblogs.com/Vae1990Silence/p/4281388.html
Copyright © 2011-2022 走看看