Reverse Linked List II
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.
Partial list reversal.
1) When the linked list is empty or a node, return to
2) Get the list length and check the M,n range.
3) The head section retains the linked list before the M-node. Second retains the node between [M,n], including m,n two nodes. Next retains the node after the N node.
4) Use **list to conveniently give null after the end of the first part. First is to facilitate the processing of the second paragraph list.
/** * definition for singly-linked list. * struct listnode { * int val; * struct listnode *next; * }; */struct listnode* reversebetween (Struct ListNode* head, int m, int n) { if ( head == null | | head->next == NULL ) { return head; } int len = 0; struct ListNode *pLen = head; for ( ; pLen; pLen = pLen->next ) { len++; } if ( m < 1 | | n > len ) { Return head; } struct listnode *first = head; struct ListNode **list = &head; int cnt = 1; for ( ; cnt < m; cnt++ ) { list = & (*list)->next; first = first- >next; } *list = NULL; struct listnode *second = null; struct ListNode *next = NULL; for ( ; cnt <= n; cnt++ ) { next = first->next ; first->next = second; second = first; first = next; } first = head; while ( first != null && first->next != NULL ) { first = first->next; } if ( head != NULL ) { first-> next = second; } else { head = second; } first = head; while ( first != NULL && first->next != NULL ) { first = first->next; } first->next = next; return head;}
[Leetcode]92. Reverse Linked List II