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 };
  • 相关阅读:
    排序题目
    力扣二分法题目
    力扣动态相似题目
    875爱吃香蕉的珂珂
    410分割数组的最大值
    1335工作计划的最低难度
    287寻找重复数
    69X的平方根
    力扣相似题目
    解决Linux虚拟机内 /mnt/hgfs路径下文件为空问题
  • 原文地址:https://www.cnblogs.com/LUO77/p/5677274.html
Copyright © 2011-2022 走看看