//设有数据集合Data,其值均为整型,Data无序且含有重复值
//要求:通过Data的值创建一个(不考虑含重复值)的升序单向链表
//例:Data={3,2,2,8,4,7,6,9}
//out:2,2,3,4,6,7,8,9
#include<stdio.h>
#include<stdlib.h>
#define N 8
typedef struct node{
int data;
struct node *next;
}ElemSN;
ElemSN *Createlink(int a[])
{
ElemSN *h,*p,*q,*np;
h=NULL;
for(int i=0;i<N;i++){
np=(ElemSN *)malloc(sizeof(ElemSN));
np->data=a[i];
np->next=NULL;
for(p=h;p&&p->data<a[i];q=p,p=p->next);//找到临界结点
np->next=p;
if(p==h){//头插
h=np;
}
else{//中间尾插
q->next=np;
}
}
return h;
}
void Printlink(ElemSN *h)
{
ElemSN *p;
for(p=h;p;p=p->next){
printf("%4d",p->data);
}
}
int main()
{
int a[N]={3,2,2,8,4,7,6,9};
ElemSN *head;
//根据功能创建链表
head=Createlink(a);
//输出
Printlink(head);
return 0;
}
//依照上例,创建一个去除重复值并且升序的链表
#include<stdio.h>
#include<stdlib.h>
#define N 8
typedef struct node{
int data;
struct node *next;
}ElemSN;
ElemSN *Createlink(int a[])
{
ElemSN *h,*p,*q,*np;
h=NULL;
for(int i=0;i<N;i++){
np=(ElemSN *)malloc(sizeof(ElemSN));
np->data=a[i];
np->next=NULL;
for(p=h;p&&p->data<a[i];q=p,p=p->next);
np->next=p;
if(p&&p->data==a[i]){
continue;
}
else{
if(p==h){//头插
h=np;
}
else{//中间尾插
q->next=np;
}
}
}
return h;
}
void Printlink(ElemSN *h)
{
ElemSN *p;
for(p=h;p;p=p->next){
printf("%4d",p->data);
}
}
int main()
{
int a[N]={3,2,2,8,4,7,6,9};
ElemSN *head;
//创建链表
head=Createlink(a);
//输出
Printlink(head);
return 0;
}