用头插、尾插、按顺序插入创建一个不带头节点的链表

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#define N 10

typedef struct Node
{
	int data;
	struct Node *next;
}Node, *pNode;

/*尾插法*/
void create_list_rear(pNode *h)
{
	srand(time(NULL));
	pNode p, q;
	p = q = *h = (pNode)calloc(1,sizeof(Node));
	p->next = NULL;
	int count = 0;
	while (count!=N){
		++count;
		if (count == 1){
			p->data = rand()%100;
			printf("%d ", p->data);
		}
		else{
			p = (pNode)calloc(1, sizeof(Node));
			p->data = rand() % 100;
			printf("%d ",p->data);
			p->next = NULL;
			q->next = p;
			q = p;
		}
	}
	printf("\n");
}

/*头插法*/
void create_list_front(pNode *h)
{
	pNode p;
	p = *h = (pNode)calloc(1,sizeof(Node));
	p->next = NULL;
	int count = 0;
	while (count != N){
		++count;
		if (count == 1){
			p->data = rand() % 100;
			printf("%d ", p->data);
		}
		else {
			p = (pNode)calloc(1,sizeof(Node));
			p->data = rand() % 100;
			printf("%d ", p->data);
			p->next = *h;
			*h = p;
		}
	}
	printf("\n");
}
/*顺序插入法*/
void create_list_sequence(pNode *h)
{
	pNode p, q, r=NULL;
	p = q = *h = (pNode)calloc(1,sizeof(Node));
	p->next = NULL;
	int count = 0;
	while (count != N){
		++count;
		if (count == 1){
			p->data = rand()%100;
			printf("%d ", p->data);
		}
		else{			
			r = (pNode)calloc(1,sizeof(Node));
			r->data = rand() % 100;
			printf("%d ", r->data);
			p = q = *h;
			while (p ->next != NULL && p->data < r->data ){
				q = p;
				p = p->next;
			}
			if (p->data >= r->data){
				if (p == q){
					r->next = *h;
					*h = r;
				}
				else {
					r->next = p;
					q->next = r;
				}
			}
			else{
				p->next = r;
				r->next = NULL;
			}
		}
	}
	printf("\n");
}

void printList(pNode h)
{
	while (h != NULL){
		printf("%d ",h->data);
		h = h->next;
	}
	printf("\n");
}

int main()
{
	pNode List = NULL;
	/*尾插法*/
	printf("尾插法:原数列的顺序为:\n");
	create_list_rear(&List);
	printf("链表的顺序为:\n");
	printList(List);

	/*头插法*/
	printf("头插法:原数列的顺序为:\n");
	create_list_front(&List);
	printf("链表的顺序为:\n");
	printList(List);

	/*顺序插法*/
	printf("顺序插法:原数列的顺序为:\n");
	create_list_sequence(&List);
	printf("链表的顺序为:\n");
	printList(List);
	return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值