leetcode Reverse Linked List II

来源:互联网 发布:压缩文件解压软件 编辑:程序博客网 时间:2024/06/07 06:26

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

一.这道题主要是对于少于等于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
原创粉丝点击