C语言 简单链表创建 排序 输出

#include<stdio.h>
#include<malloc.h>//为动态分配提供函数库
typedef struct node {
	int num;//数据域
	struct node *next;//后继指针
}node;
void create();//创建链表
void sort();//排序
void print();//输出
node *head = NULL;//初始化链表头指针
int main(void)
{
	create();//调用创建函数

	return 0;
}
void create()
{
	head = (node*)malloc(sizeof(node));//动态分配内存
	if (head == NULL)//分配失败时退出程序
		return NULL;
	node *q, *p;
	p = head;
	p->num = -1;
	while (1) {
		q = (node*)malloc(sizeof(node));
		if (q == NULL)
			return NULL;
		q->next = NULL;
		scanf("%d", &q->num);
		if (q->num == -1)//输入-1时程序停止输入
			break;
		p->next = q;
		p = q;
	}
	free(q);//释放无用结点的内存
	q = NULL;//避免野指针
	p->next = NULL;

	sort();
}
void sort()
{
	node *q;
	int judge = -1;
	node sorting;
	while (1) {
		judge = 0;
		q = head->next;
		while (q->next) {
			if (q->num > q->next->num)
			{
				judge = 1;
				sorting.num = q->num;
				q->num = q->next->num;
				q->next->num = sorting.num;
			}
			q = q->next;
		};
		if (!judge)
			break;
	}
	print();
}
void print()
{
	node *p = head->next;
	while (p) {
		printf("%d\t", p->num);
		p = p->next;
	}
}

还有链表的增删查改,有空再发!!

或者留言,可以私发

猜你喜欢

转载自blog.csdn.net/mathew_leung/article/details/79795909
今日推荐