链表的创建与插入

好久没写博客了,今天写一个链表的创建与插入,老师没给我们题目,只好自己顺便写了

题目是:已知一个从小到大排列的数列,现在给你一个数,要你将它插进去,使数列还是从小到大排列。

代码:

#include<stdio.h>
#include<stdlib.h>//malloc头文件 
struct node//定义结构 
{
	int data;
	struct node *next;
};
int main()
{
  struct node *head=NULL,*p,*q,*t;
  int n,i,a;
  scanf("%d",&n);
  for(i=1;i<=n;i++)//创建链表 
  {
  scanf("%d",&a);
  p=(struct node *)malloc(sizeof(struct node));
  p->data=a;
  p->next=NULL;
  if(head==NULL)
  head=p;
  else
  q->next=p;
  q=p;	
  }	
  scanf("%d",&a);
  t=head;
  while(t!=NULL)//插入数字 
  {
  	if(t->next==NULL||t->next->data>a)
  	{
  	p=(struct node *)malloc(sizeof(struct node));
  	p->data=a;
  	p->next=t->next;
  	t->next=p;
  	break;
	}
	t=t->next;
  }
  t=head;
  while(t!=NULL)//输出链表 
  {
  	printf("%d ",t->data);
  	t=t->next;
  }
  getchar();getchar();//吸收\n 
  return 0;
}

错误信息:

错误原因:

没写“;”;加上“;”

运行信息:

posted @ 2018-05-11 20:17  袁中  阅读(532)  评论(1编辑  收藏  举报