Reverse Linked List II

来源:互联网 发布:淘宝卖家下载什么软件 编辑:程序博客网 时间:2024/04/30 23:32
/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public:    ListNode *reverseBetween(ListNode *head, int m, int n) {        if(m==n)        {            return head;        }        m=m-1;        n=n-1;        ListNode* start=NULL;ListNode* end=NULL;        ListNode* pre=NULL;        ListNode* cur=head;        ListNode* next=head->next;        for(int i=0;i<m;++i)        {            pre=cur;            cur=next;            next=next->next;        }        start=pre;        for(int i=0;i<(n-m);++i)        {            cur->next=pre;            pre=cur;            cur=next;            next=next->next;        }end=cur->next;        cur->next=pre;        if(start==NULL)        {            head->next=end;            return cur;        }        else        {            start->next->next=end;            start->next=cur;            return head;        }            }};

0 0
原创粉丝点击