首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Leetcode 92 Reverse Linked List II

Leetcode 92 Reverse Linked List II

作者头像
triplebee
发布2018-01-12 14:59:19
4630
发布2018-01-12 14:59:19
举报

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* reverseBetween(ListNode* head, int m, int n) {
        ListNode* res=new ListNode(0);
        res->next=head;
        ListNode* pre=res;
        for(int i=0;i<m-1;i++) pre=pre->next;
        ListNode* p=pre->next;
        ListNode* temp;
        for(int i=0;i<n-m;i++)
        {
            temp=p->next;
            p->next=temp->next;
            temp->next=pre->next;
            pre->next=temp;
            
        }
        
        return res->next;
    }
};
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2016-09-28 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档