• 反转链表和反转链表2


     LeetCode 206. Reverse Linked List

    Reverse a singly linked list.

    Example:

    Input: 1->2->3->4->5->NULL
    Output: 5->4->3->2->1->NULL
    

    Follow up:

    A linked list can be reversed either iteratively or recursively. Could you implement both?

    思路:

    C++代码:

    ListNode* reverseList(ListNode* head)
    {
        ListNode* prev = NULL;
        while (head)
        {
            ListNode* next = head->next;
            head->next = prev;
            prev = head;
            head = next;
        }
        return prev;
    }

     

     

    LeetCode 92. Reverse Linked List II

    Reverse a linked list from position m to n. Do it in one-pass.

    Note: 1 ≤ m ≤ n ≤ length of list.

    Example:

    Input: 1->2->3->4->5->NULL, m = 2, n = 4
    Output: 1->4->3->2->5->NULL

    思路:

     

    C++代码:

    ListNode* reverseBetween(ListNode* head, int m, int n)
    {
        ListNode dummy = ListNode(-1), * prev = &dummy, * cur;
        dummy.next = head;
        for (int i = 0; i < m - 1; i++)
        {
            prev = prev->next;
        }
        cur = prev->next;
        for (int i = 0; i < n - m; i++)
        {
            ListNode* tmp = prev->next;
            prev->next = cur->next;
            cur->next = cur->next->next;
            prev->next->next = tmp;
        }
        return dummy.next;
    }

     注:ListNode dummy = ListNode(-1)而不是ListNode dummy = new ListNode(-1); 可以防止内存泄露,省去手动释放内存的过程。

  • 相关阅读:
    循环链表版本-----约瑟夫环
    插入排序
    队列的模板
    数据结构-栈-进制转换
    括号匹配
    两个有序链表合成一个有序链表
    希尔排序
    java-MD5-加密
    java使用Test测试接口类
    将将List json 转成List<?>实体
  • 原文地址:https://www.cnblogs.com/zkfopen/p/11176666.html
Copyright © 2020-2023  润新知