zoukankan      html  css  js  c++  java
  • Reverse Linked List II

    /**
     * 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=head;
            if(m==n) return res;
            
            int i=1;
            ListNode * pre=NULL;   //记录待反转链表的前驱,注意,带反转链表从头开始的情况,没有前驱
            ListNode * left;   //记录待反转链表的开始
            if(m>1) {
                pre=head;
                while(i<m-1){
                pre=pre->next;
                i++;
                }
             left = pre->next;
            } 
            else left = head;
            
            i=0;
            ListNode *post=left;   //记录待反转链表的后继,注意赋初值为left,而不是head,pre之类的
            while(i<n-m+1){
                post=post->next;
                i++;
            }
            
            ListNode *right=reverselist(left,n-m+1); //记录待反转链表的结束
            
            if(pre) pre->next =right;
            else res = right;
            
            while(right->next){
                right=right->next;
            }
            
            right->next=post;
            return res;
        }
        
        //把head开始长度为l的拉链,反转
          ListNode* reverselist(ListNode* head,int l) 
        {
                  ListNode * pre=NULL;
                  ListNode * cur=head;
                  ListNode * post=NULL;
                  int i=0;
            
                  while(i<l){
                      post = cur->next;
                      cur->next = pre;
                      pre = cur;
                      cur = post;
                      i++;
                  }
                  return pre;
        }
    };
      
  • 相关阅读:
    STOAdiary20110312抉择
    STOA静夜思
    STOAOO
    STOAdiary20110316翻译的一天
    STOAdiary20110318疲倦与激情
    STOAdiary20110314平静的一天
    Silverlight入门
    Postgres远程访问配置
    [收藏]Jquery客户端拖拽排序方法
    整理的邮件一个邮件发送类
  • 原文地址:https://www.cnblogs.com/julie-yang/p/4688184.html
Copyright © 2011-2022 走看看