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 ≤M≤NLength 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