LeetCode: Reverse Linked List II

来源:互联网 发布:哈佛 歧视 知乎 编辑:程序博客网 时间:2024/05/17 14:26

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->NULLm = 2 and n = 4,

return 1->4->3->2->5->NULL.

Note:
Given mn satisfy the following condition:

1 ≤ m ≤ n ≤ length of list.

/** * 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;        int index = 1;        ListNode *pre = NULL, *cur = head, *start = NULL, *next = NULL,*tail = NULL;        while(index != m && cur != NULL)        {            start = cur;            cur = cur->next;            index++;        }        tail = cur;        while(cur != NULL && index <= n)        {            index++;            next = cur->next;            cur->next = pre;            pre = cur;            cur = next;                    }        tail->next = cur;        if(start != NULL)            start->next = pre;        else            return pre;                return head;             }};


Round 2:

class Solution {public:    ListNode *reverseBetween(ListNode *head, int m, int n) {        if(m == n)            return head;        ListNode *pre = NULL, *cur = head, *front = NULL, *prefront = NULL;        int count = 1;        while(cur != NULL)        {            if(count >= m && count <= n)            {                if(count == m)                {                    prefront = pre;                    front = cur;                }                else if(count == n)                {                    if(m == 1)                        head = cur;                    else                        prefront->next = cur;                    front->next = cur->next;                                    }                ListNode *temp = cur->next;                cur->next = pre;                pre = cur;                cur = temp;                count++;            }            else            {                pre = cur;                cur = cur->next;                count++;            }        }        return head;    }};


0 0
原创粉丝点击