博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
将两个有序链表合并为一个新链表
阅读量:4502 次
发布时间:2019-06-08

本文共 2329 字,大约阅读时间需要 7 分钟。

#include 
#include
typedef struct _Node{ int value; struct _Node *next;}Node;Node *MergeList(Node *listA, Node *listB);void PrintList(Node *head);int main(){ Node lista, nodea, listb, nodeb, nodec; lista.value = 2; nodea.value = 2; nodec.value = 19; lista.next = &nodea; nodea.next = &nodec; nodec.next = NULL; listb.value = 3; nodeb.value = 4; listb.next = &nodeb; nodeb.next = NULL; Node *listc = MergeList( &lista, &listb ); PrintList(listc); system("pause"); return 0;}/*@brief merge two sorted lists to a new list which is sorted , too !@param in : listA @param in : listB@return pHead the new list of head*/Node *MergeList(Node *listA, Node *listB){ Node *pHead = (Node *)malloc(sizeof(Node)); if ( NULL == pHead ) { printf("error, line %d malloc failed \n", __LINE__); return NULL; } pHead->next = NULL; Node *pNode = NULL; Node *pLink = pHead; // if the list head just is without data use listA = NULL != listA ? listA->next : listA; listB = NULL != listB ? listB->next : listB; while( NULL != listA && NULL != listB ) { pNode = (Node *)malloc(sizeof(Node)); if ( NULL == pNode ) { printf("error, line %d malloc failed \n", __LINE__); return pHead; } if ( listA->value <= listB->value ) { pNode->value = listA->value; listA = listA->next; } else { pNode->value = listB->value; listB = listB->next; } pNode->next = NULL; pLink->next = pNode; pLink = pLink->next; } while ( NULL != listA ) { pNode = (Node *)malloc(sizeof(Node)); if ( NULL == pNode ) { printf("error, line %d malloc failed \n", __LINE__); return pHead; } pNode->value = listA->value; listA = listA->next; pNode->next = NULL; pLink->next = pNode; pLink = pLink->next; } while ( NULL != listB ) { pNode = (Node *)malloc(sizeof(Node)); if ( NULL == pNode ) { printf("error, line %d malloc failed \n", __LINE__); return pHead; } pNode->value = listB->value; listB = listB->next; pNode->next = NULL; pLink->next = pNode; pLink = pLink->next; } return pHead;}void PrintList(Node *head){ if ( NULL == head ) { printf("error, list is NULL\n"); return ; } // if the list head just is without data use head = head->next; while( NULL != head ) { printf("%d\t", head->value); head = head->next; } printf("\n");}

 

转载于:https://www.cnblogs.com/haihuahuang/p/4273233.html

你可能感兴趣的文章
简单的响应式布局的实现
查看>>
jQuery(属性操作)
查看>>
Python之路【第九篇】:Python面向对象
查看>>
background和background-image一点小区别
查看>>
ASCII码对照表
查看>>
HackerRank "Training the army" - Max Flow
查看>>
jquery next()方法
查看>>
深入剖析js命名空间函数namespace
查看>>
SQLHelper
查看>>
用标准Struts2+mvc写的用户管理
查看>>
Cocos2d-x 3.0 编译出错 解决 error: expected &#39;;&#39; at end of member declaration
查看>>
Ubuntu12.04下载Repo
查看>>
python基础教程_学习笔记10:异常
查看>>
MATLAB——scatter的简单应用
查看>>
linux下复制粘贴快捷键
查看>>
什么是对象
查看>>
记录开发小程序
查看>>
WinSock服务程序
查看>>
巴西柔术第五课:过腿
查看>>
文件的操作
查看>>