zoukankan      html  css  js  c++  java
  • 剑指offer-重新排序数组,倒置链表

    重新排序数组

    描述

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

    思路:

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

    代码:

    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; 
    }
    
  • 相关阅读:
    linux hosts.equiv设置解析
    linux 普通synflood攻击防范网络参数设置
    电脑如何刻录光盘的方式
    Linux系统服务详解
    linux下history命令显示历史指令记录的使用方法
    tkinter模块常用参数
    python使用tkinter做界面之颜色
    python进行linux系统监控
    Windows 系统cmd设置添加静态路由方式
    PyCharm在win10的64位系统安装实例
  • 原文地址:https://www.cnblogs.com/void-lambda/p/12357353.html
Copyright © 2011-2022 走看看