部分翻转链表Reverse Linked List II

来源:互联网 发布:php 获取根目录 编辑:程序博客网 时间:2024/05/24 05:56
/** * 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) {        ListNode*ahead=new ListNode(-1);        ahead->next=head;        ListNode*p1=ahead;        ListNode*p2=head;        for(int i=1;i<m;i++)        p1=p1->next;        for(int i=1;i<n;i++)        p2=p2->next;        ListNode*p3=p2->next;        p2->next=NULL;        p1->next=reverse(p1->next);        ListNode*q=p1->next;        while(q->next)q=q->next;        q->next=p3;        return ahead->next;            }    ListNode* reverse(ListNode* head) {        ListNode*rhead=NULL;        ListNode*p=head;        ListNode*pre=NULL;        while(p)        {            ListNode*pnext=p->next;            if(pnext==NULL)rhead=p;            p->next=pre;            pre=p;            p=pnext;        }        return rhead;    }};

原创粉丝点击