码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] Reverse Linked List II

时间:2015-08-05 14:51:51      阅读:112      评论:0      收藏:0      [点我收藏+]

标签:c++   leetcode   

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.

解题思路:

题意为翻转指定区间的链表节点。这道题本身还是挺简单的。对于前m-1个节点正序拷贝即可。对于中间n-m+1个节点,逆序拷贝。对于剩下的节点直接连上。

/**
 * 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) {
        if(m>=n || m<=0){
            return head;
        }
        ListNode* myHead = new ListNode(0);
        ListNode* tail = myHead;
        ListNode* p = head;
        int c = 0;
        while(c < m - 1 && p!=NULL){  //m-1个正序
            tail->next = p;
            tail = tail->next;
            p = p->next;
            c++;
        }
        ListNode* q = tail;
        if(p!=NULL){
            tail = p;
        }
        while(c < n && p!=NULL){    //n-m+1个逆序
            ListNode* k = p->next;
            p->next = q->next;
            q->next = p;
            p = k;
            c++;
        }
        tail->next = p;             //剩下的直接连接
        p = myHead->next;
        delete myHead;
        return p;
    }
};


版权声明:本文为博主原创文章,未经博主允许不得转载。

[LeetCode] Reverse Linked List II

标签:c++   leetcode   

原文地址:http://blog.csdn.net/kangrydotnet/article/details/47296271

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!