How to realize partial list inversion by LeetCode
This article will explain in detail how LeetCode achieves partial list inversion. Xiaobian thinks it is quite practical, so share it with you as a reference. I hope you can gain something after reading this article.
Partial list inversion.
1) When the linked list is empty or a node, it can be returned
2) Get the length of the linked list and check the range of m,n.
3) The head section retains the linked list before m nodes. The second retains nodes between [m,n], including m,n nodes. next Keep the nodes after n nodes.
4) Use **list to facilitate the end of the first part followed by NULL. The first is to facilitate the processing of the second linked 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 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;} About "LeetCode how to achieve partial list inversion" This article is shared here, I hope the above content can be of some help to everyone, so that you can learn more knowledge, if you think the article is good, please share it for more people to see.