leetcode Reverse Linked List II

    这道题是给定了位置的逆序。

一.这道题主要是对于少于等于2个节点   和   多于2个节点的情况进行区别。少于2个节点的时候presubhead 是NULL。

当presubhead是null的时候,tail才是头。

presubhead不是null,head才是头。

二.代码

class Solution {
public:
    ListNode* reverseBetween(ListNode* head, int m, int n) {
        ListNode *subhead,*presubhead,*tail;
        ListNode *cur,*pre,*temp;
        subhead = head;
        presubhead = NULL;
        
        int i=1;
        if(!head)
            return NULL;
        if(m==n)
            return head;
            
        while(i!=m)
        {
            presubhead = subhead;
            subhead = subhead->next;
            i++;
        }   //结束后subhead presubhead 即指向第m 和m-1
        cur = subhead->next;
        pre = subhead;
        while(i!=n)
        {
            temp = cur->next;
            cur->next = pre;
            pre = cur;
            cur = temp;
            i++;
        }
        tail = pre;   //cur存着tail的next
        if(presubhead!=NULL)
        {
            presubhead->next = tail;
            subhead->next = cur;
            return head;
        }
        else
        {
            
            subhead->next =cur;
            return tail;
        }
    }
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值