leetcode_c++:链表:Reverse Linked List II (092)

来源:互联网 发布:java编译器中文安卓版 编辑:程序博客网 时间:2024/06/05 06:24

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.


O(n)


class Solution {public:    ListNode* reverseBetween(ListNode* head, int m, int n) {        ListNode* mhead=new ListNode(-1),*prev,*cur;        mhead->next=head;        for(int i=0;i<m-1;i++)            mhead=mhead->next;        prev=mhead->next;        cur=prev->next;        for(int i=m;i<n;i++){            prev->next=cur->next;            cur->next=mhead->next;            mhead->next=cur;            cur=prev->next;        }        return m==1? mhead->next:head;    }};
0 0
原创粉丝点击