博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Reverse Linked List II
阅读量:2194 次
发布时间:2019-05-02

本文共 2001 字,大约阅读时间需要 6 分钟。

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.

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public: ListNode *reverseList(ListNode *root)    {        if(!root||!root->next)            return root;        ListNode *p,*q,*tem;        p = root;        q = NULL;        while(p)        {            if(!q)            {                p = p->next;                q = root;                q->next = NULL;                continue;            }          tem = p;          p   = p->next;          tem->next = q;          q = tem;        }        return q;    }        ListNode *reverseBetween(ListNode *head, int m, int n)    {        if(NULL==head||NULL==head->next||m==n)            return head;        ListNode *mp = head; // the point to the head of list        ListNode *np = head; // the tail of list        ListNode *mp1;       // the head of list         ListNode *np1;        ListNode *newhead;                while(n!=1&&n--)            np = np->next;        if(m==1&&NULL==np->next)           return reverseList(head);                  if(m==1&&NULL!=np->next)        {            np1 = np->next;            np->next = NULL;            newhead = reverseList(head);            head->next = np1;            return newhead;        }                            while(m!=2&&m--)            mp = mp->next;                mp1 = mp->next;        np1 = np->next;        np->next = NULL;        reverseList(mp1);                                mp->next = np;        mp1->next = np1;        return head;                       }};
注意几点:
1. 调用reverseList()时, 尾结点要置NULL, 否则不符合调用规则,程序会超时
2. 考虑情况较多, 均分别处理
~m=n
~m=1, n<len
~m=1, n = len
~n=len
~1<m<n<len

转载于:https://my.oschina.net/vintnee/blog/640481

你可能感兴趣的文章
Leetcode C++《热题 Hot 100-29》22.括号生成
查看>>
Leetcode C++《热题 Hot 100-47》236.二叉树的最近公共祖先
查看>>
Leetcode C++《热题 Hot 100-48》406.根据身高重建队列
查看>>
《kubernetes权威指南·第四版》第二章:kubernetes安装配置指南
查看>>
Leetcode C++《热题 Hot 100-49》399.除法求值
查看>>
Leetcode C++《热题 Hot 100-51》152. 乘积最大子序列
查看>>
Leetcode C++ 《第181场周赛-1》 5364. 按既定顺序创建目标数组
查看>>
Leetcode C++ 《第181场周赛-2》 1390. 四因数
查看>>
阿里云《云原生》公开课笔记 第一章 云原生启蒙
查看>>
阿里云《云原生》公开课笔记 第二章 容器基本概念
查看>>
阿里云《云原生》公开课笔记 第三章 kubernetes核心概念
查看>>
阿里云《云原生》公开课笔记 第四章 理解Pod和容器设计模式
查看>>
阿里云《云原生》公开课笔记 第五章 应用编排与管理
查看>>
阿里云《云原生》公开课笔记 第六章 应用编排与管理:Deployment
查看>>
阿里云《云原生》公开课笔记 第七章 应用编排与管理:Job和DaemonSet
查看>>
阿里云《云原生》公开课笔记 第八章 应用配置管理
查看>>
阿里云《云原生》公开课笔记 第九章 应用存储和持久化数据卷:核心知识
查看>>
linux系统 阿里云源
查看>>
国内外helm源记录
查看>>
牛客网题目1:最大数
查看>>