设head指向一个数据域值升序有序的非空单向链表,将关键字为key的结点插入,使原链表依然有序

#include<stdio.h>
#include<stdlib.h>
typedef struct node{
	int data;
	struct node *period;
	struct node *next;
}ElemSN;
ElemSN *Createlink(int *Data,int n)
{
	ElemSN *np,*head=NULL,*tail;
	for(int i=0;i<n;i++){//创建新结点 
		np=(ElemSN *)malloc(sizeof(ElemSN));
		np->data=*(Data+i);
		np->next=np->period=NULL;
		if(!head){//挪头指针 
			head=tail=np;
		}
		else{//挂链挪尾指针 
			tail->next=np;
			np->period=tail;
			tail=tail->next;
		}
	}
	return head;
} 
ElemSN *Delkeynode(ElemSN *h,ElemSN *key)
{
	ElemSN *p;
	for(p=h;p&&p->data<=key->data;p=p->next);
	if(p==h){//头插
		p->period=key;
		key->period=NULL;
		key->next=p; 
		h=key;
	}
	else{
		if(!p)
		{//尾插
			for(p=h;p->next;p=p->next);
			p->next=key;
			key->next=NULL;
			key->period=p; 
		}
		else
		{//中间插
			key->period=p->period;
			p->period=key;
			key->period->next=key;
			key->next=p;
		}
	}
	return h;
}
void Printlink(ElemSN *head)
{
	ElemSN *p;
	for(p=head;p;p=p->next)
		printf("%5d",p->data);//正向输出 
}
int main()
{
	int n,i;
	ElemSN *key;
	int *Data;
	ElemSN *head=NULL;
	printf("Please input the n:");
	scanf("%d",&n);//输入数组长度 
	Data=(int *)malloc(n*sizeof(int));
	printf("Please input the Data[i]:");
	for(i=0;i<n;i++){//输入数组元素  有序 
		scanf("%d",Data+i);
	}
	printf("Please input the key:");
	key=(ElemSN *)malloc(1*sizeof(ElemSN));
	scanf("%d",&(key->data));
	head=Createlink(Data,n);//创建双向链表 
	head=Delkeynode(head,key);
	Printlink(head);//输出 
	free(Data);//释放内存空间 
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_42727102/article/details/89007913