• 合并单链表,输出单链表中间元素,判断是否有环等


    本博文内容为单链表相关的笔试题,转载请注明转载处,否则必究

    1. 合并两个有序的单链表成一个有序的单链表

    方法分为递归实现与非递归实现,两种方法都不额外开辟 内存空间

    链表的数据结构在本博客的单链表逆转,约瑟夫环等 

    递归实现:

    //递归实现合并两个有序单链表
    LinkNode* merge_list(LinkNode *pHead1, LinkNode *pHead2)
    {
    	if(pHead1==NULL)
    		return pHead2;
    	if(pHead2==NULL)
    		return pHead1;
    	if(pHead1==NULL && pHead2==NULL)
    		return NULL;
    	LinkNode *pMergedHead=NULL;
    	if(pHead1->value<pHead2->value)
    	{
    		pMergedHead=pHead1;
    		pMergedHead->next = merge_list(pHead1->next, pHead2);
    	}
    	else 
    	{
    		pMergedHead=pHead2;
    		pMergedHead->next=merge_list(pHead1, pHead2->next);
    	}
    	return pMergedHead;
    }
    

    非递归实现:

    //非递归实现合并两个有序单链表(不额外开辟空间)
    LinkNode* non_merge_list(LinkNode *pHead1, LinkNode *pHead2)
    {
    	if(pHead1==NULL)
    		return pHead2;
    	if(pHead2==NULL)
    		return pHead1;
    	if(pHead1==NULL && pHead2==NULL)
    		return NULL;
    	LinkNode *pMergedHead = NULL;
    	LinkNode *q=NULL;
    	if(pHead1->value<pHead2->value)
    	{
    		pMergedHead=pHead1;
    		pHead1=pHead1->next;
    	}
    	else
    	{
    		pMergedHead=pHead2;
    		pHead2=pHead2->next;
    	}	
    	q=pMergedHead;
    	while(pHead1 && pHead2)
    	{
    		if(pHead1->value<pHead2->value)
    		{
    			q->next=pHead1;
    			pHead1=pHead1->next;
    		}
    		else
    		{
    			q->next=pHead2;
    			pHead2=pHead2->next;
    		}
    		q=q->next;
    	}
    	if(pHead1)
    	{
    		while(pHead1)
    		{
    			q->next=pHead1;
    			q=q->next;
    			pHead1=pHead1->next;
    		}
    	}
    	if(pHead2)
    	{
    		while(pHead2)
    		{
    			q->next=pHead2;
    			q=q->next;
    			pHead2=pHead2->next;
    		}
    	}
    	return pMergedHead;
    }
    

    2 输出单链表中的中间元素(若链表节点个数为偶数,则输出中间两个的任意一个)

    思路:利用两个指针从头节点开始遍历,一个走一步,一个走两步,当一次走两步的指针走到链表末尾时,此时一次走一步的指针就指向链表的中间节点

    代码如下:

    LinkNode* print_mid_node(LinkNode *pHead)
    {
    	LinkNode *pOne = pHead, *pTwo = pHead;
    	while(1)	
    	{
    		pOne = pOne->next;
    		pTwo = pTwo->next->next;
    		if(pTwo==NULL || pTwo->next==NULL)
    			return pOne;
    	}
    }
    

    3 判断单恋表是否有环

    思路与第二题一样,只是结束条件不一样,如果当一次走一步的指针等于一次走两步的指针时,则表示该链表有环

    代码如下:

    bool is_circle_list(LinkNode *pHead)
    {
    	LinkNode *pOne = pHead, *pTwo = pHead;
    	while(1)
    	{
    		pOne = pOne->next;
    		pTwo = pTwo->next->next;
    		if(pOne == pTwo)
    			return true;
    		if(pTwo==NULL || pTwo->next==NULL)
    			return false;
    	}
    }
    




  • 相关阅读:
    关于 php json float 出现很多位的问题
    做 Excel 的 XML schema.xsd
    笔记:Python 默认参数必须指向不变对象
    Bartender 使用 Excel xlsx 数据库时出现 0x800A0E7A
    Javascript 中 的 for ... in 和 for ... of 差别
    关于跨域资料收集 (2019-01-11)
    ThinkPHP3 和 ThinkPHP5 不是一个团队做的
    记录一下:给电推剪改锂电池
    为你的Web程序加个启动画面
    前端不为人知的一面--前端冷知识集锦 前端已经被玩儿坏了!像console.log()可以向控制台输出图片
  • 原文地址:https://www.cnblogs.com/xinyuyuanm/p/3206499.html
Copyright © 2020-2023  润新知