上一篇介绍了单链表的基础实现,https://blog.csdn.net/genzld/article/details/81060013
这篇文章介绍的是两个有序链表的合并,后面还会相应的介绍排序,无需链表的有序合并等
/*
制作信息:
制作日期:2018-7-18
制作人 :TheShyclear
制作内容:简单数据结构_有序单链表的合并
版本 :8.0
内容信息:
初始化 :只要初始化某个头节点,其data域为0,当在pos=1插入数据时才修改
解题思路:通过定义另一个头指针来重新改变两个链表的节点指向,
采用递归的方法:比较两个链表头节点的data的大小,取小,
然后使其m_pNext为头节点,进行相同的处理,直至为NULL。
问题易错位置
:当我们给每个函数传入头节点参数的时间,我们不能直接对该头节点
进行操作,会丢失链表的头
调试 :head1为空(不初始化为空),或head2为空,或两者都为空,
和两个链表都有数据
*/
#include
#include
#include
#include
typedef int Elemtype;
typedef struct ListNode
{
Elemtype data;//值域
ListNode *m_pNext;//指针域
}ListNode,*PListNode;
ListNode* BuyNode()
{
ListNode* p = (ListNode*)malloc(sizeof(ListNode));
if(NULL == p)
{
printf("buynode is error:\n");
exit(1);
}
memset(p,0,sizeof(ListNode));
return p;
}
void InitList(PListNode &p)
{
p = BuyNode();
p->m_pNext = NULL;
p->data = 0;
}
int GetLength(PListNode &head)//问题出现:不能直接操作head节点
{
int count = 0;
PListNode s = head;
while(s!=NULL)
{
count+=1;
s=s->m_pNext;
}
return count;
}
void InsertList(PListNode &p,Elemtype x,int pos)
// pos=1的位置只能插入一次,多次的话不会插入节点,仅仅只是修改第一个节点的data,也就是我们不能在头节点之前插入节点
{
if(pos<1 || pos>GetLength(p)+1)
{
printf("input pos is error:\n");
exit(1);
}
PListNode s = p;//头节点 s
if(pos == 1)
{
p->data = x;
p->m_pNext = NULL;
}
else
{
while(pos-2)
{
s = s->m_pNext;
--pos;
}//s指向前驱
PListNode r =s->m_pNext;
PListNode q = BuyNode();
q->data = x;
s->m_pNext = q;
q->m_pNext = r;
}
}
PListNode Merge(PListNode &phead1,PListNode &phead2)
{
PListNode s = phead1;
PListNode r = phead2;
if(s == NULL)
return r;
else if(r == NULL)
return s;
PListNode pMergehead = NULL;
if(s->data < r->data)
{
pMergehead = s;
pMergehead->m_pNext = Merge(s->m_pNext,r);
}
else
{
pMergehead = r;
pMergehead->m_pNext = Merge(s,r->m_pNext);
}
return pMergehead;
}
void Show_List(PListNode &head)
{
PListNode s =head;
while(s != NULL)
{
printf("%d ",s->data);
s = s->m_pNext;
}
}
void main()
{
PListNode my = NULL,mys = NULL,myt = NULL;//定义三个链表的头,
InitList(my);
//InitList(mys);
InitList(myt);
for(int i=1;i<5;++i)
{
InsertList(my,i+10,i);
}
Show_List(my);
printf("\n");
// InsertList(mys,100,1);
myt = Merge(my,mys);
Show_List(myt);
}