LeetCode | Reverse Linked List II

100 篇文章 0 订阅
13 篇文章 0 订阅

这道链表反转题也是搞的我焦头烂额,好久没有写链表了,注意记忆这些

  1. Reverse Linked List II QuestionEditorial Solution My Submissions Total Accepted: 78774 Total Submissions: 274380 Difficulty: Medium
    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.

直接贴代码吧

//看到这样的题目需要分析一下具体有哪些种类,而不是盲目地将其分类
class Solution {
public:
    ListNode* reverseBetween(ListNode* head, int m, int n) {
        //分为m=1或者n=linklist.size()-1或者二者都是或者二者都不是
        ///(ㄒoㄒ)/~~4种情况 
//      ListNode* temp=head,a,b,apre,bpre;
//      int count=0;
//      while(temp!=NULL){
//          count++;
//          if(count==m) a=temp;
//          else if(count==n) b=temp;
//      }
//      
//      temp=head;
//      while(temp!=NULL){
//          //找到了a之前的节点 
//          if(temp->next==a) {
//              apre=temp;
//          }
//      }
//      上面这种放弃
        //由于leetcode上链表都是从第一项开始的
        //所以必须得手动添加一个链表头 
        ListNode root(-1);
        root.next=head;

        ListNode* pre=&root;
        //注意链表也可以通过for循环来实现遍历 
        //不要觉得只有while(temp->next!=NULL)这种 
        for(int i=1;i<m;i++)
        pre=pre->next;

        //开启第二链表头,从这里引出链表到目的节点 
        //cur表示当前指针 
        ListNode* head2=pre;
        //注意我们要以何种方式进行遍历
        //从第m个数开始需要被交换[3,5]
        //这里pre=pre->next之后,pre->val=3,pre->next->val=5;
        //再通过下面的交换就可以替换3和5的位置
        pre=pre->next;
        ListNode* cur=pre->next;
        //对之后的进行遍历
        for(int i=m;i<n;i++){
            pre->next=cur->next;

            //头部插入数据
            //如果没有那一步pre=pre->next;那么这里cur->next=head2->next即(pre->next),就会落到5上,这样head2->next就没有被交换
            cur->next=head2->next;
            head2->next=cur;

            cur=pre->next;
        }
        return root.next;

    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值