合并单链表,输出单链表中间元素,判断是否有环等
2013-07-21 15:48
239 查看
本博文内容为单链表相关的笔试题,转载请注明转载处,否则必究
链表的数据结构在本博客的单链表逆转,约瑟夫环等
递归实现:
代码如下:
代码如下:
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; } }
相关文章推荐
- 合并单链表,输出单链表中间元素,判断是否有环等
- 四道有趣的单链表面试题(单链表反序、找出链表的中间元素、链表排序、判断一个单链表是否有环)
- 四道有趣的单链表面试题(单链表反序、找出链表的中间元素、链表排序、判断一个单链表是否有环) (转)
- 四道有趣的单链表面试题(单链表反序、找出链表的中间元素、链表排序、判断一个单链表是否有环)
- 四道有趣的单链表面试题(单链表反序、找出链表的中间元素、链表排序、判断一个单链表是否有环) (转)
- 四道有趣的单链表面试题(单链表反序、找出链表的中间元素、链表排序、判断一个单链表是否有环)
- 四道有趣的单链表面试题(单链表反序、找出链表的中间元素、链表排序、判断一个单链表是否有环
- 四道有趣的单链表面试题(单链表反序、找出链表的中间元素、链表排序、判断一个单链表是否有环)
- 用C语言实现判断两个数组中是否有相同的元素,有就输出“有”,没有则输出“没有”
- 数组的创建/查找数组里面的内容/添加数组中元素/使用指定的字符串把数组链接起来/判断数组内是否有指定的数组元素/四种遍历进行输出数组中的元素有哪些
- 判断两个数组是否有相同的元素?有输出“有”,没有输出“没有”
- 判断两个等长数组中元素是否一样,如不一样,输出不一样的元素
- 单链表查找倒数第N个元素&输出中间元素
- 建立一个带附加头结点的单链表.实现测长/打印/删除结点/插入结点/逆置/查找中间节点/查找倒数第k个节点/判断是否有环
- 队列用链表实现(建立,插入新元素,删除元素,读取元素,全部删除,全部读出,判断是否为空,清空)
- 判断一个单项链表是否有循环,如果有循环输出循环点
- 链表的中间节点和判断链表是否为环形链表
- 如何判断链表是否存在环和求链表中间节点
- 【LeetCode91-100】编码种数,逆转单链表,IP地址转化,中序遍历二叉树,生成二叉搜索树,计算二叉树个数,交叉string【hard】,判断二叉搜索树是否合法,恢复二叉树(有两个元素被交换)
- 判断两个数组中是否有相同元素,有就输出有,没有就输出没有