02-线性结构1-两个有序链表序列的合并-函数题

02-线性结构1-两个有序链表序列的合并-函数题

解题代码

void Attach(ElementType Data,List *rear);
void Free(List L);

List Merge( List L1, List L2 )
{
	List head,rear,front,LT1=L1,LT2=L2;
	head=(List)malloc(sizeof(struct Node));
	front=rear=head;
	head->Next=NULL;
    while(LT1->Next&&LT2->Next){
    	if(LT1->Next->Data>LT2->Next->Data){
    		Attach(LT2->Next->Data,&rear);
    		LT2=LT2->Next;
		}else if(LT1->Next->Data<LT2->Next->Data){
    		Attach(LT1->Next->Data,&rear);
    		LT1=LT1->Next;
		}else{
			Attach(LT1->Next->Data,&rear);
    		Attach(LT2->Next->Data,&rear);
    		LT2=LT2->Next;
    		LT1=LT1->Next;
		}
	}
	while(LT1->Next){
		Attach(LT1->Next->Data,&rear);
		LT1=LT1->Next;
	}
	while(LT2->Next){
		Attach(LT2->Next->Data,&rear);
		LT2=LT2->Next;
	}
	Free(L1);
	Free(L2);
	return front;
}

void Attach(ElementType Data,List *rear)
{
	List add;
	add=(List)malloc(sizeof(struct Node));
	add->Next=NULL;
	add->Data=Data;
	(*rear)->Next=add;
	(*rear)=add;
}

void Free(List L)
{
	List L1=L->Next,LN;
	while(L1){
		LN=L1->Next;
		free(L1);
		L1=LN;
	}
	L->Next=NULL;
}

测试结果

在这里插入图片描述

问题整理

1.段错误的可能导致原因:输出链表的最后一个node的next没有赋NULL。
2.
3.

发布了47 篇原创文章 · 获赞 2 · 访问量 1364

猜你喜欢

转载自blog.csdn.net/Aruasg/article/details/104893681