首页 > 代码库 > [LeetCode]92. Reverse Linked List II
[LeetCode]92. Reverse Linked List II
92. 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.
部分链表反转。
1)链表为空或者一个节点时,返回即可
2)获取链表长度,进行m,n范围检查。
3)head部分保留m节点之前的链表。second保留[m,n]之间的节点,包括m,n两个节点。next保留n节点后的节点。
4)使用**list方便给第一部分的结束结束后置NULL。first是方便第二段链表的处理。
/** * 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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。