[leetcode-92-Reverse Linked List II]

本文介绍了一种在原地且仅一次遍历的情况下反转链表中从位置m到n的方法,并给出了两种实现方式的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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->NULL, m = 2 and n = 4,
return 1->4->3->2->5->NULL.
Note:
Given m, n satisfy the following condition:
1 ≤ m ≤ n ≤ length of list.

思路:

感觉自己的思路太啰嗦,那也放这儿吧,记录一下:

用index时刻关注位置,看是否到达m或者n。

当没有到达m的时候,只需向后移动指针,到达m的时候,要断开左右两部分指针。

然后用头插法在左边链表最后的位置插入m到n之间的结点。

需要格外注意的就是边界的情况。

ListNode* reverseBetween(ListNode* head, int m, int n)
 {
     ListNode dumb(0);
     dumb.next = head;
     if(m == n) return head;
     ListNode* preM = &dumb;//保存m之前结点
     ListNode* pM = head,*pN = head ,*temp = head;
     int index=1;
     while(pN != NULL)
     {
         if(index < m)
         {
             index++;
             preM = pM;
             pM = pM->next;
             pN = pN->next;
         }
         else if(index >= m && index <= n)
         {
             temp = pN->next;
             pN->next = preM->next;
             preM->next =pN;
             pN = temp;
             index++;
         }
         else if(index > n)        break;
     }
        pM->next = pN;
   return dumb.next;
}

再来学习一下大牛的简介高效代码:

ListNode *reverseBetween2(ListNode *head, int m, int n) {
    if(m==n)return head;
    n-=m;
    ListNode prehead(0);
    prehead.next=head;
    ListNode* pre=&prehead;
    while(--m)pre=pre->next;
    ListNode* pstart=pre->next;
    while(n--)
    {
        ListNode *p=pstart->next;
        pstart->next=p->next;
        p->next=pre->next;
        pre->next=p;
    }
    return prehead.next;
}

参考:

https://discuss.leetcode.com/topic/4980/share-my-14-lines-c-solution

 

转载于:https://www.cnblogs.com/hellowooorld/p/6681538.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值