[Leetcode series] flipped Linked List II

Source: Internet
Author: User

Given a linked list and two integers m, n, flip the M node of the linked list to the N node (counting starts from 1 ).

For example, for a given linked list: 1-> 2-> 3-> 4-> 5-> null, and m = 2, n = 4.

Returns 1-> 4-> 3-> 2-> 5-> null.

Assume that M and N meet the constraints: 1 ≤MNLength less than or equal to the length of the linked list.

Note: you cannot use extra space, and you can only use the traversal link table once.

 

Algorithm ideas:

The flip process can be divided into three steps:

Invert the pointing relationship of adjacent nodes; that is, 1-> 2 <-3 <-4 5-> null

Point Node 1 to node N (4); that is, 1-> 4-> 3-> 2 5-> null

Point the MTH node (2, cache required) to the n + 1 node (5). That is, 1-> 4-> 3-> 2-> 5-> null

 

/** * 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(!head || m == n)            return head;        ListNode *p = head;        int count = 1;        while(count < m-1)        {            p = p->next;            count++;        }        ListNode *p1;        if(m == 1)            p1= p;        else        {            p1 = p->next;            count++;        }        ListNode *last = p1;        ListNode *p2 = p1->next;        ListNode *tmp = NULL;        while(p2 && count < n)        {            tmp = p2->next;            p2->next = p1;            p1 = p2;            p2 = tmp;            count++;        }        last->next = tmp;        if(m == 1)            head = p1;        else            p->next = p1;        return head;    }};

 

[Leetcode series] flipped Linked List II

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.