zoukankan      html  css  js  c++  java
  • 反转链表

        反转链表是一个常见的面试题,现在出现了N多种的变形,各种增加难度。今天看到了一个从m反转到n的,于是手写代码试了试。发现要想把所有情况覆盖全达到bug free还是挺难的。于是,根据各种反转链表题总结了一些比较简练的代码。比较:接口限定的反转链表

    // 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;
    }
  • 相关阅读:
    Storyboard中segue使用总结
    Present ViewController Modally
    UILabel设置富文本格式显示
    objective-c 中随机数的用法 (3种:arc4random() 、random()、CCRANDOM_0_1() )
    ios中static的作用
    NSBundle的使用,注意mainBundle和Custom Bundle的区别
    OC的基础语法OC继承和复合语言特性目标动作回调
    动态规划-被3整除的子序列
    A
    Coins POJ
  • 原文地址:https://www.cnblogs.com/codingmylife/p/2655684.html
Copyright © 2011-2022 走看看