zoukankan      html  css  js  c++  java
  • leetCode(11):Reverse linked list II 分类: leetCode 2015-06-18 15:16 154人阅读 评论(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;
            }
    };


  • 相关阅读:
    Cookie和Session知识扫盲
    Nmap扫描原理与用法
    物理cpu与逻辑cpu的理解
    shell常用命令ping
    shell如何获取本地ip
    数据库52条SQL语句性能优化
    Linux Shell查看物理CPU个数、核数、逻辑CPU个数
    cf1225D Power Products cf1471D. Strange Definition
    cf 1389 E. Calendar Ambiguity
    cf 1420 D. Rescue Nibel!
  • 原文地址:https://www.cnblogs.com/zclzqbx/p/4687106.html
Copyright © 2011-2022 走看看