链表反转的几种形式

// From curr reverse to end, return reversed linked list head.
ListNode *unguarded_reverse(ListNode *prev, ListNode *curr, ListNode *end)
{
    ListNode *next = NULL;
    
    while (curr != end)
    {
        next = curr->next;
        curr->next = prev;
        prev = curr;
        curr = next;
    }
    
    return prev;
}
 
// Reverse linked list from m to n, return head.
// For example:
// Given 1->2->3->4->5->NULL, m = 2 and n = 4,
// return 1->4->3->2->5->NULL.
ListNode *reverse_between(ListNode *head, int m, int n) 
{
    if (head == NULL || m <= 0 || n <= 0)
    {
        return NULL;
    }
    
    if (m >= n) return head;
    
    ListNode **backup = &head, *p = head, *q = head;
    
    // Move p to the mth node, q to the nth node.
    while (p != NULL && --m) backup = &p->next, p = p->next;
    while (q != NULL && --n) q = q->next;
    
    // If move success.
    if (m == 0 && n == 0 && p != NULL && q != NULL)
    {
        *backup = unguarded_reverse(q->next, p, q->next);
    }
    
    return head;
}
 
// Reverse every k group in linked list, return head.
// For example,
// Given this linked list: 1->2->3->4->5
// For k = 2, you should return: 2->1->4->3->5
// For k = 3, you should return: 3->2->1->4->5
ListNode *reverse_k_group(ListNode *head, int k) {
    if (head == NULL || k < 0) return NULL;
    
    int count = 0;
    
    // Count all node num.
    for (ListNode *p = head; p != NULL; p = p->next)
    {
        ++count;
    }
    
    for (int i = 1; i + k - 1 <= count; i += k)
    {
        head = reverse_between(head, i, i + k - 1);
    }
    
    return head;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值