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

leetCode(11):Reverse linked list II

时间:2015-06-18 17:26:10      阅读:110      评论:0      收藏:0      [点我收藏+]

标签:

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) {
        int i=1;
    	if(head==NULL)
    		return NULL;
    	if(head->next==NULL)
    	    return head;
    	if(m==n)
    		return head;
    	
    	ListNode* p=head;
    	ListNode* pM=NULL;
    	ListNode* p1=NULL;
    	ListNode* p2=NULL;
    	ListNode* p3=NULL;
    	ListNode* tail=NULL;
    	if(m==1)
    	{
    		p1=head;
    		tail=p1;
    		p2=p1->next;
    		p3=p2->next;
    		if(p3==NULL)
    		{
    			head=p2;
    			p2->next=p1;
    			p1->next=NULL;
    			return head;
    		}
    	}
    	
    	while(i<n-1)
    	{
    		if(i+1==m)
    		{
    			pM=p;//反转起点上一结点
    			tail=pM->next;
    			p1=pM->next;//反转起点
    			p2=p1->next;
    			p3=p2->next;			
    		}
    		if(i>=m-1)
    		{
    			p2->next=p1;
    			p1=p2;
    			p2=p3;
    			if(p3)
    				p3=p3->next;
    		}
    		else
    			p=p->next;	
    		i++;
    	}
    	if(m==1)
    	{
    		p2->next=p1;
    		tail->next=p3;
    		return p2;
    	}
    	if(n==2)
    	{
    		p2->next=p1;
    		p1->next=p3;
    		return p2;
    	}
    	pM->next=p1;
    	tail->next=p2;
    	return head;
        }
};


leetCode(11):Reverse linked list II

标签:

原文地址:http://blog.csdn.net/walker19900515/article/details/46548487

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