链表头插和尾插

链表头插和尾插

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

struct list
{
	int data;
	struct list *next;
};
typedef struct list ST;
/*
ST *creat_link()//尾插
{
	int a;
	ST *h,*p,*q;

	h = (ST *)malloc(sizeof(ST)*1);  //头结点
	p = h;

	scanf("%d",&a);
	while(a != 0)
	{
		q = (ST *)malloc(sizeof(ST)*1); //产生新节点
		q->data = a;
		p->next = q; // 将新节点连接到表尾
		p = q;       // 将 p 指向当前表尾
		scanf("%d",&a);
	}
	p->next = NULL;   //表尾置空
	return h;
}
*/
ST *creat_link()  //头插
{
	int a;
	ST *h,*q;

	h = (ST *)malloc(sizeof(ST)*1);  //头结点
	h->next = NULL;

	scanf("%d",&a);
	while(a != 0)
	{
		q = (ST *)malloc(sizeof(ST)*1); //产生新节点
		q->data = a;
		q->next = h->next;  //将新节点插到表头
		h->next = q;        // 将头节点的指针指向新节点
		scanf("%d",&a);
	}
	return h;
}


int main()
{
	ST *head,*q;

	head = creat_link();

	q = head->next;

	while(q != NULL)
	{
		printf("%d ",q->data);
		q = q->next;
	}

	return 0;
}

当输入 2  3  4  5  0时,头插结果为5  4  3  2,尾插的结果为 2  3  4  5

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值