Title:
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
.
Note:
Given m, n satisfy the following condition:
1 ≤ m ≤ n ≤length of list.
Insertion method
Ideas:
Step 1: Find the location of the M node and maintain a node p before the M node so that it is inserted here.
Step 2: Invert until n nodes. The inverse method is to read one node at a time, insert it into the previous position (P->next) of the current linked list M node, and then the original m nodes receive the next node read.
Complexity: O (N), requires several auxiliary pointers, Space O (1)
Attention:
1. The insertion must be inserted in the previous position of the current m node, which is the next position of the P node that was previously maintained.
Tmp->next = p->next; It must be p->next here, because each insertion is in the previous position of M, and the first position after p.
2. Notice the initialization and definition methods of the head node and the first nodes (the difference node and the linked list)
ListNode dummyhead (0);d ummyhead.next = head; listnode* p = &dummyhead;
3. The distinction between two data structure nodes consists of a data field that holds the elements and a pointer field that holds the address of the successor node. Listnode* p; If P is a pointer to the first element of the linear table.P->next represents a pointer to the next node. ListNode p (0); If P is a single node within a linked list.P.next represents a value that holds the address information for another node within the P node.
* struct ListNode {* int val; * ListNode *next; * listnode (int x): Val (x), Next (NULL) {} *};
AC Code:
/** * Definition for singly-linked list. * struct ListNode {* int val; * ListNode *next; * listnode (int x): Val (x), Next (NULL) {} *}; */class Soluti On {public: listnode *reversebetween (listnode *head, int m, int n) { //Insert Method if (head = = NULL) return null; ListNode dummyhead (0); Dummyhead.next = head; listnode* p = &dummyhead; for (int i = 1; i < m; i++) { p = p->next; } Head = p->next; Head is the M node, p is the previous node of M ///execute insert for (; m < n; m++) { listnode* tmp = head->next; Head->next = tmp->next; Tmp->next = p->next; It must be p->next here, because each insertion is in the previous position of M, and the first position after p. p->next = tmp; } return dummyhead.next;} ;
[C + +] leetcode:62 Reverse Linked List II