数据结构之栈的部分总结

先进后出,(形象的类似为碟盘子,取盘子)

仅允许在栈顶top进行插入、删除操作,另一端不能进行插入、删除操作的称为栈底bottom

顺序栈

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

# define MAXSIZE 20;

typedef struct{
	int a[MAXSIZE];
	int top;
}SeqStack;

//建立栈空间 ,初始化栈顶指针 
SeqStack *InitStack(){
	SeqStack *s;
	s = (SeqStack *)malloc(sizeof(SeqStack)); 
	s->top = -1;
	return s; 
}

//判空栈 
int Empty(SeqStack *s){
	if(s->top == -1){
		return true;
	}
	else return false;
}

//入栈
int Push(SeqStack *s,int x){
	if(s->top == MAXSIZE - 1) return 0;
	else{
		s->top++;
		s->a[s->top] = x;
		return 1;
	}
} 

//出栈
int Pop(SeqStack *s,int *x){
	if(s->top == -1) return 0;
	else{
		*x = s->a[s->top];
		s->top--;
		return 1;
	}
}

//取栈顶元素 
int GetTop(SeqStack *s){
	if(Empty(s)) return 0;
	else{
		return s->a[s->top];
	}
}

要点:

  • 入栈时,判断栈是否满s->top == MAXSIZE-1
  • 出栈,读栈顶元素时,判断栈是否为空 s->top == -1
  • 出栈, s->top--; 入栈,s->top--

链栈(避免栈上溢)

栈顶,top,链表最后一个结点;栈底,bottom,链表的第一个结点

一个链栈可由栈顶指针top唯一确定

判断条件

top->next //栈顶元素
top->next == NULL //空栈

部分代码展示

typedef struct Stacknode{
	int data;
	struct Stacknode *next; 
}sl;

//入栈
int PushLstack(sl *top,int x){
	sl *p;
	if( (p=(sl *)malloc(sizeof(sl))) == NULL) return 0;
	p->data = x;
	p->next = top->next;
	top->next = p;
	return 1;
} 

//出栈
int PopLstack(sl *top){
	sl *p;
	int x;
	if(top->next == NULL)
	{
		//栈空 
		return ;
	}
	p = top->next;
	top->next = p->next;
	x = p->data;
	free(p);
	return x;
} 
发布了26 篇原创文章 · 获赞 6 · 访问量 1443

猜你喜欢

转载自blog.csdn.net/qiao_xi/article/details/102880853