8.13作业

链栈,自己实现一遍,但是节点存储不是整数,存储学生信息(年龄,分数,姓名)三级引用。

1、建立学生信息结构体,将data改为学生信息结构体类型。

2、循环入栈和入队。

代码展示
#include <myhead.h>
#define MAX 4
typedef struct{//学生结构体
	int age;
	float score;
	char name[20];
}stu;

typedef struct node{//节点结构体
	stu s;
	struct node *next;
}Node;

typedef struct{//栈顶结构体
	int len;
	Node *top;
}Stack,*Pstack;

typedef struct{//队列结构体
    Node *rear;
    Node *front;                                                                               
    int len;
}Queue,*Pqueue;

Pstack creat_stack(){
	Pstack p = malloc(sizeof(Stack));
	if(p==NULL){
		printf("申请空间失败!\n");
		return NULL;
	}
	p->len = 0;
	p->top = NULL;
	return p;
}

Pqueue creat_queue(){
	Pqueue p = malloc(sizeof(Queue));
	if(p==NULL){
		printf("申请空间失败!\n");
		return NULL;
	}
	p->len = 0;
	p->rear = NULL;
	p->front = NULL;
	return p;
}

int stack_insert(Pstack p,stu s){
	if(p==NULL){
		printf("链表不存在!\n");
		return -1;
	}
	Node *t = malloc(sizeof(Node));
	t->s.age = s.age;
	t->s.score = s.score;
	strcpy(t->s.name,s.name);
	t->next = p->top;
	p->top = t;
	p->len++;
	return 0;
}

int queue_insert(Pqueue p,stu s){
	if(p==NULL){
		printf("队列不存在!\n");
		return -1;
	}
	Node *t = malloc(sizeof(Node));
	t->s.age = s.age;
	t->s.score = s.score;
	strcpy(t->s.name,s.name);
	if(p->rear==NULL){
		p->rear = t;
		p->front = t;
	}else{
		p->rear->next = t;
		p->rear = t;
	}
	t->next = NULL;
	p->len++;
	return 0;

}

int stack_output(Pstack p){
	if( p==NULL || p->len == 0 ){ 
		printf("链表不存在或者为空!\n");
		return -1;
	}
	printf("学生信息如下:\n");
	Node *t = p->top;
	for(int i=0;i<p->len;i++){
		printf("年龄:%d\t成绩:%.2f\t姓名:%s\n",t->s.age,t->s.score,t->s.name);
		t = t->next;
	}
	return 0;
}

int queue_output(Pqueue p){
	if(p==NULL || p->len == 0 ){
		printf("队列不存在或者为空!\n");
		return -1;
	}
	Node *t = p->front;
	printf("学生信息如下:\n");
	for(int i=0;i<p->len;i++){
		printf("年龄:%d\t成绩:%.2f\t姓名:%s\n",t->s.age,t->s.score,t->s.name);
		t = t->next;
	}
	return 0;
}

int main(int argc, const char *argv[])
{  	
	printf("链栈的输入输出:\n");
	Pstack L = creat_stack();
	stu s[MAX] = {{18,89,"王五"},
                  {20,90,"张三"},
                  {19,96,"李玲"},                        
                  {18,88,"赵柳"}};
    for(int i=0;i<MAX;i++){
        stack_insert(L,s[i]);
    }
    stack_output(L);
	printf("链式队列的输入输出:\n");
	Pqueue P = creat_queue();
    for(int i=0;i<MAX;i++){
        queue_insert(P,s[i]);
    }
	queue_output(P);


	return 0;
}

运行结果

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值