当前位置 博文首页 > Inmaturity_7的博客:408计算机考研--数据结构--栈学习(C语言)

    Inmaturity_7的博客:408计算机考研--数据结构--栈学习(C语言)

    作者:[db:作者] 时间:2021-07-16 21:46

    栈学习(C语言)

    一、栈的基本概念

    ? 栈(Stack)是只允许在一端进行插入或删除操作的线性表。首先栈是一种线性表,但限定这种线性表只能在某一端进行插入和删除操作。

    栈顶(top):线性表允许进行插入和删除的那一端。

    栈底(Bottom):固定的,不允许进行插入和删除的另一端。

    空栈:不含任何元素的空表。

    二、栈的顺序存储结构

    #include<stdio.h>
    #include<stdlib.h> 
    #define MaxSize 10 //定义栈中元素的最大个数
    
    
    typedef struct{
    	int data[MaxSize];//静态数组存放栈中元素
    	int top;//栈顶指针 
    }SqStack;
    
    //初始化栈 
    void InitStack(SqStack &S){
    	S.top=-1;
    }
    //判断栈是否为空 
    bool StackEmpty(SqStack S){
    	if(S.top==-1){
    		return true;
    	}else{
    		return false;
    	}
    }
    //入栈 
    bool Push(SqStack &S,int x){
    	if(S.top==MaxSize-1){//如果栈满返回false 
    		return false;
    	}
    	S.data[++S.top]=x;
    	return true;
    }
    //出栈 
    bool Pop(SqStack &S,int &x){
    	if(S.top==-1){//如果栈为空返回false 
    		return false;
    	}
    	x=S.data[S.top--];
    	return true;
    }
    //获取栈顶元素 
    bool GetTop(SqStack &S,int &x){
    	if(S.top==-1){//如果栈为空返回false 
    		return false;
    	}
    	x=S.data[S.top];
    	return true;
    }
    int main(){
    	SqStack S;//声明一个顺序栈(分配空间)
    	InitStack(S);
        //入栈
    	Push(S,1);
    	Push(S,2);
    	Push(S,3);
    	Push(S,4);
    	Push(S,5);
    	int x1,x2,x3,x4,x5;
        //出栈
    	Pop(S,x1);
    	Pop(S,x2);
    	Pop(S,x3);
    	Pop(S,x4);
    	Pop(S,x5);
    	printf("%d %d %d %d %d",x1,x2,x3,x4,x5);
    }
    

    三、栈的链式存储结构

    #include<stdio.h>
    #include<stdlib.h> 
    
    
    typedef struct LinkNode{
    	int data;//数据域 
    	struct LinkNode* next;//指针域 
    }LinkNode,*LinkStack;
    
    //初始化栈 
    void InitStack(LinkStack &S){
    	S=(LinkStack)malloc(sizeof(LinkNode));
    	S->next=NULL;
    }
    //判栈空
    bool EmptyStack(LinkStack &S){
    	if(S->next==NULL){
    		return true;
    	}
    	return false;
    }
    //入栈 
    bool Push(LinkStack &S,int x){
    	LinkStack newNode=(LinkStack)malloc(sizeof(LinkNode));
    	newNode->data=x;
    	newNode->next=S->next;
    	S->next=newNode;
    	return true;
    }
    //出栈
    bool Pop(LinkStack &S,int &x){
    	if(EmptyStack(S)){
    		return false;
    	}
    	LinkStack node=S->next;
    	x=node->data;
    	S->next=node->next;
    	free(node);
    	return true;
    }
    //打印链表 
    void Printf_LinkedList(LinkStack &S){
    	LinkStack temp=S->next;
    	while(temp!=NULL){
    		printf("%d->",temp->data);
    		temp=temp->next;
    	} 
    	return ;
    }
    int main(){
    	//栈头结点 
    	LinkStack head;
    	InitStack(head);
    	//入栈12345 
    	Push(head,1);
    	Push(head,2);
    	Push(head,3);
    	Push(head,4);
    	Push(head,5);
    	//出栈 
    	int x1,x2,x3,x4,x5;
    	Pop(head,x1);
    	Pop(head,x2);
    	Pop(head,x3);
    	Pop(head,x4);
    	Pop(head,x5);
    	printf("%d %d %d %d %d",x1,x2,x3,x4,x5);
    }
    
    cs