您的位置:首页 > 其它

[LeetCode]92. Reverse Linked List II

2016-09-05 21:31 447 查看
92. Reverse Linked List IIReverse 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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Code Leet