#include<stdio.h>
#include<stdlib.h>
struct node //声明结构体类型名
{
int data; //结点存放的数据
struct node *next;//指向下一个结点的指针
};
struct node *create_slist()//建立单链表的函数,返回的是头结点
{
int x;
struct node *head,*s,*r;
head=(struct node *) malloc(sizeof(struct node));//h为头结点
r=head;
scanf("%d",&x);
while(x!=-1) //输入数据时以-1作为结束标志
{
s=(struct node *)malloc(sizeof(struct node)); //结点申请得到的空间记为s
s->data=x; //s中存放的数据是x
r->next=s; //r指向的下一个结点的地址是s
r=s;
scanf("%d",&x);// 输入单链表的各个节点x
}
r->next='\0';// r指向的下一个结点为空时结束
return head;
}
void print_slist(struct node *h) //输出单链表的函数,形式参数为头结点
{
struct node *p; //定义一个结构体指针变量
p=h->next; //头结点指向的下一个结点为p
if(p=='\0') //如果头结点指向的下一个结点p为空,则输出。。。。。。
printf("Linklist is null!\n");
else //如果不为空字符
{
printf("head");
while(p!='\0')
{
printf("->%d",p->data); //输出p的数
p=p->next; //p的下一个数
}
printf("->end\n"); //输出结束标识符
}
}
void insert_node(struct node *h,int x) //插入结点的函数,x为要插入的结点
{
struct node *s,*p,*q;
s=(struct node *)malloc(sizeof(struct node)); //为s申请分配空间
s->data=x; //结点s的数据是x
q=h->next; //q初始值为第一个结点
p=q->next; //p初始值为第二个节点(q的下一个结点)
while(p!='\0')
{
if(x<=q->data&&x>=p->data) //当x满足条件时终止循环(条件是:x大于第二个节点小于第一个结点)
{
q->next=s; //在q和P中插入结点
s->next=p; //
break;
}
else
{
q=p;
p=p->next;
}
}
if(s->data<=q->data)//如果插入的值比最小值(也是最后一个值)小,则插入在最后面
{
q->next=s;
s->next=p;
}
else //如果插入的值比最大值(也就是第一个值)大,则插入在最前面
{
q=h->next; //q的初始值是第一个结点
h->next=s; //把第一个结点给s
s->next=q; //s的下一结点是q,即s放在第一位
}
}
void sort_slist(struct node *h) //从大到小排序函数
{
struct node *p,*q,*t;
t=(struct node *)malloc(sizeof(struct node));//结点node申请分配空间
q=h->next;
p=q;
while(q!='\0') //利用冒泡排序方法
{
p=q->next;
while(p!='\0')
{
if(q->data<=p->data) //交换p和q的位置
{
t->data=q->data;
q->data=p->data;
p->data=t->data;
p=p->next;
}
else
p=p->next;
}
q=q->next;
}
}
void main()
{
struct node *head;
int x; //x为要插入单链表的结点数据值
printf("建立slist并初始化,以-1为结束标志:\n");
head=create_slist(); //调用创建表函数
sort_slist(head); //调用单链表排序函数对输入的数进行排序
print_slist(head); //调用输出单链表函数输出已排序好的单链表
printf("输入插入点结点的数据值x=");
scanf("%d",&x);
printf("在链表中插入结点\n");
insert_node(head,x); //调用插入结点函数
print_slist(head); //再次调用输出单链表函数
}