链式栈,链式队列练习代码

1.链式栈

#include <stdio.h>
#include <stdlib.h>
//初始化栈
typedef struct link{
int num;
struct link * next;
}link,*plink;

struct stack{
plink top;
plink botton;
};
//创建
struct stack *create_head(void)
{
struct stack * head = (struct stack *)malloc(sizeof(struct stack));
if(head == NULL)
{
printf(“创建失败\n”);
return NULL;
}
printf(“创建成功\n”);
head->top = head->botton = NULL;

}
//压栈
void Push_stack(struct stack *head,int date)
{
plink new = (plink)malloc(sizeof(link));
if(new == NULL)
{
printf(“创建新节点失败\n”);
return ;
}
//第一次压栈
if(head->top == NULL)
{
head->top = head->botton = new;//栈顶栈底都指向新创建节点
}
else{
new->next = head->top;
head->top = new;//上移栈顶
}
new->num = date;//新结点赋值
printf("%d\n",new->num);
}
//出栈
void output(struct stack *head)
{
//先判断是否为空栈
if(head->top == NULL)
{
printf(“空栈\n”);
return ;
}
plink tmp = head->top;//从栈顶开始出
while(tmp->next != NULL)
{
printf(“出栈 %d \n”,tmp->num);
tmp = tmp->next;//下一个节点
}
printf(“栈底 %d \n”,tmp->num);
}
int main()
{
int i;
struct stack *head = create_head();
Push_stack(head,1);
Push_stack(head,2);
Push_stack(head,3);
Push_stack(head,4);
Push_stack(head,5);
output(head);
return 0;
}

2.链式队列

#include <stdio.h>
#include <stdlib.h>
//队列
typedef struct link{
int num;
struct link * next;
}Qlink;

struct queue{
Qlink *top;
Qlink *botton;
};
//创建
struct queue *create_head(void)
{
struct queue * head = (struct queue *)malloc(sizeof(struct queue));
if(head == NULL)
{
printf(“创建失败\n”);
return NULL;
}
printf(“创建成功\n”);
head->top = head->botton = NULL;
return head;
}
//入队
void Push_queue(struct queue *head,int date)
{
Qlink * new = (Qlink *)malloc(sizeof(Qlink *));
if(new == NULL)
{
printf(“创建新节点失败\n”);
return ;
}
//第一次入队
if(head->top == NULL)
{
new ->next = NULL;
head->top = head->botton = new;//栈顶栈底都指向新创建节点
}
else{
Qlink *tmp = head->top;
while(tmp->next != NULL)
{
tmp = tmp->next;//队列尾
}
tmp->next = new;
new->next = NULL;
head->botton = new;
}
new->num = date;//新结点赋值
printf("%d\n",new->num);
}
//出栈
void output(struct queue *head)
{
//先判断是否为空队列
if(head->top == NULL)
{
printf(“空栈\n”);
return ;
}
Qlink *tmp = head->top;//从栈顶开始出
while(tmp->next != NULL)
{
printf(“出队 %d \n”,tmp->num);
tmp = tmp->next;//下一个节点
}
printf(“队列底 %d \n”,tmp->num);
}
int main()
{
int i;
struct queue *head = create_head();
Push_queue(head,1);
Push_queue(head,2);
Push_queue(head,3);
Push_queue(head,4);
Push_queue(head,5);
output(head);
return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值