数据结构(栈和队列)

一、栈

用数组实现栈

#include <stdio.h>
#define MaxSize 5
typedef struct Stack{
	int data[MaxSize];
	int pre;
}Stack;
//初始栈
void Init(Stack *stack){
	stack->pre = -1;
}
//入栈操作
void Push(Stack *stack,int x){
	//判断栈是否已满
	if(stack->pre == MaxSize-1){
		printf("栈已满\n");
		return;
	}
	stack->pre = stack->pre+1;//指针向上走一位
	stack->data[stack->pre] = x;
}
//出栈操作
void Pop(Stack *stack){
	if(stack->pre == -1){
		printf("栈已空\n");
		return;
	}
	printf("%d\n",stack->data[stack->pre]);
	stack->pre = stack->pre-1;
}
int main()
{
	Stack stack;
	Init(&stack);
	Push(&stack,5);
	Push(&stack,7);
	Push(&stack,4);
	Push(&stack,2);
	Pop(&stack);
	Pop(&stack);
	Pop(&stack);
	Pop(&stack);
    return 0;
}

用链表实现栈

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

typedef struct Node{
	int data;
	struct Node *next;
}LinkNode;
//初始化链表(栈)的头节点
void Init(LinkNode *node){
	node->next = NULL;//头节点的next初始化为NULL,表示栈为空
}
//入栈操作(在链表头部插入新节点)
void Push(LinkNode *head,int value){
	//创建新的节点
	LinkNode *newNode = (LinkNode *)malloc(sizeof(LinkNode));
	newNode->data = value;
	newNode->next = NULL;
	//将新节点插入到头部(栈顶)
	newNode->next = head->next;
	 head->next = newNode;
}
//出栈操作(删除链表头部节点并打印其值)
void Pop(LinkNode *head){
	if(head->next == NULL){//栈为空是直接返回
		return;
	}
	LinkNode *temp = head->next;//临时保存栈顶节点
	printf("%d\n",temp->data);//打印栈顶元素
	head->next = temp->next;//移除栈顶节点
	free(temp);
}
int main()
{
	LinkNode *head = (LinkNode *)malloc(sizeof(LinkNode));//为头节点分配内存
	Init(head);//初始化头节点
	Push(head,1);
	Push(head,2);
	Push(head,3);
	Pop(head);
	Pop(head);
    return 0;
}

二、队列

用数组实现队列

#include <stdio.h>
#define MaxSize 5
typedef struct Queue{
    int arr[MaxSize];
    int r; //出
    int p; //入
}Queue;
void init(Queue *queue){
    queue->r = -1;
    queue->p = -1;
}
//数据添加
void insert(Queue *queue,int value){
    if(queue->p - queue->r == MaxSize){
        printf("队列已满\n");
        return;
    }
    queue->p= queue->p+1;
    queue->arr[queue->p] = value;
}
//取出数据
void chu(Queue *queue){
    if(queue->p - queue->r == 0){
        printf("队列已空\n");
        return;
    }
    queue->r= queue->r+1;
    printf("%d\n",queue->arr[queue->r]);
}
int main(){
    Queue queue;
    init(&queue);
    insert(&queue,5);
    insert(&queue,7);
    insert(&queue,4);
    insert(&queue,2);
    insert(&queue,0);
    insert(&queue,3);
    chu(&queue);
    chu(&queue);
    chu(&queue);
    chu(&queue);
    chu(&queue);
    chu(&queue);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值