您的位置:首页 > 其它

用指针实现链表--插入排序

2014-03-24 12:06 148 查看
★实验任务

有n(1<=n<=1000)个整数,a1,a2,…an已经按照从小到大顺序排列好,现在另外给

m(1<=m<=1000)个整数x1,x2,….xm,请将这些数插入到序列中,并使新的序列仍然是从

小到大顺序。

★数据输入

输入第一行是n和m,第二行是已经有序的n个数的数列。第三行是待m个待插入的整

数数。

★数据输出

输出插入新的元素后的数列,数据间以空格隔开。

输入示例

3 1

1 2 3

4

输出示例

1 2 3 4

第一次使用链表,发现自己还有很多不懂,Go Go 加油!

#include<stdio.h>

#include<malloc.h>

#define ListItemint

typedef struct node *link;

typedef struct node{

ListItemelement;

linknext;

}Node;

typedef struct llist *List;

typedef struct llist{

linkfirst;

}Llist;

List ListInit()

{

ListL=(List)malloc(sizeof(*L));

L->first=0;

returnL;

}

link NewNode()//新节点

{

linkp;

p=(link)malloc(sizeof(Node));

returnp;

}

void ListInsert(int l,List L)//插入排序

{

linkp,y;

ListItemx,t;

for(inti=0;i<l;i++)

{

scanf("%d",&x);

t=0;

p=L->first;

for(;p&&x>p->element;p=p->next)

{

t++;

if(p->next&&x<=p->next->element)

break;

if(!p->next) break;

}

y=NewNode();

y->element=x;

if( t )

{

y->next=p->next;

p->next=y;

}

else

{

y->next=L->first;

L->first=y;

}

}

}

int main()

{

intn,m;

ListItemx;

ListL;

linkp;

while(scanf("%d%d",&n,&m)!=EOF)

{

L=ListInit();

ListInsert(n+m,L);

for(p=L->first;p;p=p->next)

{

if(p==L->first)printf("%d",p->element);

else

printf("%d",p->element );

}

printf("\n");

}

return0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐