1. 程式人生 > >連結串列的建立、合併······

連結串列的建立、合併······

#include"stdio.h"
#include"stdlib.h"
#define error 0
#define ok 1
//宣告結點
typedef struct mystruct{
	int elem;
	mystruct *pNext;

}node,*linklist;
//尋找指定元素,並返回
void Getelem(linklist L,int i,int &elem){
	linklist p=L;int j=0;
	while (p&&j<i)
	{
		p=p->pNext;
		++j;
	}
	if (!p||i<=0) goto here;
	elem=p->elem;
	here:;
	/*
	if(i==0) goto here;
	linklist p=L;
	for (int j= 0; j < i-1; j++)
	{
		p=p->pNext;
		if (!p) goto here;
	}
	elem=p->elem;
	here:;
	*/
}
//建立連結串列
void Creatlinklist(linklist &L,int n){
	//插入法建立連結串列
	L=(linklist)malloc(sizeof(node));
	linklist p;
	L->pNext=NULL;
	for (int i = n; i >0; i--)
	{
		p=(linklist)malloc(sizeof(node));
		printf("NO %d:",i);
		scanf("%d",&p->elem);
		p->pNext=L->pNext;
		L->pNext=p;
	}
	/*順序建立
	L=(linklist)malloc(sizeof(node));
	linklist p;linklist pe;p=pe=L;
	for (int i = 0; i < n; i++)
	{
		p=(linklist)malloc(sizeof(node)) ;
		printf("NO %d:",i+1);
		scanf("%d",&p->elem);
		pe->pNext=p;
		pe=p;
		
	}
	p->pNext=NULL;
	*/
}
//插入結點
int listInsert(linklist &L,int i,int e){
	linklist p=L;
	int j=0;
	while (p&&j<i-1)
	{
		p=L->pNext;
		++j;
	}
	linklist s=(linklist)malloc(sizeof(node));
	if (!s|| j>i-1)return error;
	s->pNext=p->pNext;
	p->pNext=s;
	s->elem=e;
	return ok;
}
//刪除結點
int listDelect(linklist &L,int i,int &e){
	linklist p=L;
	int j=0;
	while (p&&j<i-1)
	{
		p=p->pNext;
		++j;
	}
	if (!p->pNext||!p||j>i-1)return error;
	/*
	while (p->pNext&&j<i-1)
	{
		p=p->pNext;
		++j;
	}
	if (!p->pNext||j>i-1)return error;
	*/
	linklist q=p->pNext;
	e=q->elem;
	p->pNext=q->pNext;
	free(q);
	return ok;
}
//將兩個非遞減連結串列合成一個非遞減連結串列
void Merge(linklist &la,linklist &lb,linklist &lc){
	lc=la;
	linklist pa=la->pNext,pb=lb->pNext,pc=lc;
	while (pa&&pb)
	{
		if (pa->elem <= pb->elem)
		{
			pc->pNext=pa;
			pa=pa->pNext;
		}else
		{
			pc->pNext=pb;
			pb=pb->pNext;
		}
		pc=pc->pNext;
	}
	pc->pNext=pa?pa:pb;
	/*
	垃圾演算法:
	while (pa)
	{
		pc->pNext=pa;
		pa=pa->pNext;
		pc=pc->pNext;
	}
	while (pb)
	{
		pc->pNext=pb;
		pb=pb->pNext;
		pc=pc->pNext;
	}
	*/
	free(lb);//刪去頭部節點
}