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

Reverse Linked List II

时间:2014-10-24 14:33:58      阅读:154      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   io   os   ar   for   sp   

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的处理,对链表创建头结点tmphead,对应于上面例子,lt->val=1;lt_next->val=2;rt->val=4;rt_next->val=5;

         然后对(lt_next,rt)之间的链表翻转(lt_next->next=rt_next);

code:

bubuko.com,布布扣
/**
 * 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 tmphead(-1);
        tmphead.next=head;
        ListNode *cur=head;
        ListNode *lt,*lt_next,*rt,*rt_next;
        int count=1;
        
        if(m==n)
            return head;
        
        while(cur)
        {
            if(m==1)
            {
                lt=&tmphead;
                lt_next=head;
            }
            else if(count==m-1)
            {
                lt=cur;
                lt_next=cur->next;
            }
            
            if(count==n)
            {
                rt=cur;
                rt_next=cur->next;
            }
            
            ++count;
            cur=cur->next;
        }
        
        rt->next=NULL;
        while(lt_next)
        {
            ListNode *tmp=lt_next->next;
            lt_next->next=rt_next;
            rt_next=lt_next;
            lt_next=tmp;
        }
        
        lt->next=rt_next;
        return tmphead.next;
    }
};
View Code

思路二:简化思路一,不必记录n所对应的节点,通过循环直接逆转链表;

code:

bubuko.com,布布扣
/**
 * 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 *lt=NULL;
        ListNode *lt_next=head;
        
        for(int i=0;i<m-1;++i)
        {
            lt=lt_next;
            lt_next=lt_next->next;
        }
        
        ListNode *link;
        ListNode *link_next=lt_next->next;
        ListNode *lt_nextsave=lt_next;
        for(int i=m+1;i<=n;++i)
        {
            link=link_next;
            link_next=link_next->next;
            link->next=lt_next;
            lt_next=link;
        }
        
        lt_nextsave->next=link_next;
        
        if(lt)
            lt->next=lt_next;
        else
            return lt_next;
        return head;
    }
};
View Code

 

Reverse Linked List II

标签:style   blog   http   color   io   os   ar   for   sp   

原文地址:http://www.cnblogs.com/chengyuz/p/4048039.html

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