zoukankan      html  css  js  c++  java
  • 【leetcode】92. 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.

     1 /**
     2  * Definition for singly-linked list.
     3  * struct ListNode {
     4  *     int val;
     5  *     ListNode *next;
     6  *     ListNode(int x) : val(x), next(NULL) {}
     7  * };
     8  */
     9 class Solution {
    10 public:
    11     ListNode* reverseBetween(ListNode* head, int m, int n) {
    12         int d=n-m;
    13         if(head==NULL||head->next==NULL||d<=0)
    14             return head;
    15        
    16         ListNode* p=head,*bfp=p;
    17         ListNode* q=head;
    18         for(int i=0;i<m-1;i++){
    19             bfp=p;
    20             p=p->next;
    21         }
    22         ListNode* revhead=p;
    23         ListNode* bf=p,*bh=NULL;
    24         p=p->next;
    25         d--;
    26         while(p->next!=NULL&&d!=0){
    27             d--;
    28             bh=p->next;
    29             p->next=bf;
    30             bf=p;
    31             p=bh;
    32             
    33         }
    34         bh=p->next;
    35         p->next=bf;
    36         bfp->next=p;
    37         revhead->next=bh;
    38         if(m!=1)
    39             return head;
    40         else return p;
    41     }
    42 };
  • 相关阅读:
    2019春季学期第四周作业
    2019年春季学期第三周作业+预习作业
    2019第一周作业2
    2019第一周作业1
    寒假作业3(抓老鼠啊~亏了还是赚了?)
    nginx负载均衡
    性能优化建议
    数据库主从配置
    php魔术方法
    图片轮播
  • 原文地址:https://www.cnblogs.com/LUO77/p/5677274.html
Copyright © 2011-2022 走看看