首页 > 编程语言 > 详细

剑指offer-重新排序数组,倒置链表

时间:2020-02-24 16:14:33      阅读:85      评论:0      收藏:0      [点我收藏+]

重新排序数组

描述

根据特定条件重新排序数组,如将奇数排到偶数前面。将负数排到偶数前面。

思路:

设置两个指针,前指针和后指针。将条件作为一个函数传入,两个指针向中间移动,不符和条件的交换。

代码:

bool fun(int n)
{
    if (n % 2 == 0)
        return 0;
    else
        return 1;
}
void ReorderArray(int* arr, int len, bool (*fun)(int n))
{
    int* phead = arr;
    int* pend = arr + len - 1;
    while (phead < pend)
    {
        while (phead < pend && fun(*phead) == 1)
        {
            phead++;
        }
        while (phead < pend && fun(*pend) == 0)
        {
            pend--;
        }
        if (phead < pend)
        {
            int temp = *phead;
            *phead = *pend;
            *pend = temp;
        }
    }
}
    void ReorderArrayWith01(int* arr, int len)
    {
        ReorderArray(arr, len, fun);
    }

倒置链表

思路:

1.循环方式需要用三个指针,p,为了连接到前面的节点,需要ppre,为了防止断链,需要pnext。
2.递归方式
技术分享图片

问题规模缩小
技术分享图片
结果
技术分享图片
假设2开头的链表已经反转成功,接下来只要将2的next指向1,而1的next指向null即可。
其实只要将两个节点反过来即可。
技术分享图片
技术分享图片

代码:

ListNode* ReverseList(ListNode* head)
{
    if (head == NULL)
        return NULL;
    if (head->next == NULL)
        return head;
    ListNode* reversedhead = NULL;
    ListNode* p = head;
    ListNode* ppre = NULL;
    ListNode* pnext = NULL;
    while (p!=NULL)
    {
        pnext = p->next;
        p->next = ppre;
        ppre = p;
        p = pnext;
    }
    reversedhead = ppre;
    return reversedhead;
}
ListNode* ReverseListR(ListNode* head)
{
    if (head == NULL ||head->next==NULL)
        return head;
    ListNode *res=ReverseListR(head->next);
    head->next->next = head;
    head->next=NULL;
    return res; 
}

剑指offer-重新排序数组,倒置链表

原文:https://www.cnblogs.com/void-lambda/p/12357353.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!