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;
}
转载于:https://blog.51cto.com/11998200/1846546