栈的实现(顺序表和链表)

来源:互联网 发布:notes plus 知乎 编辑:程序博客网 时间:2024/06/02 05:32

#include <stdio.h>
//栈的最大存储数量
#define StackSize 100
//栈的数据类型
typedef int DataType;
//栈的结构体
typedef struct {
 DataType data[StackSize];
 int top;
} SeqStack;
//初始化
void StackInit(SeqStack *stack)
{
 stack->top=-1;
}
//判断栈满
int StackFull(SeqStack *stack)
{
 if(stack->top==StackSize-1)
  return 0;
 else
  return -1;
}
//判断栈空
int StackEmpty(SeqStack *stack)
{
 if(stack->top==-1)
  return 0;
 else
  return -1;
}
//将数据放入栈中
void StackPush(SeqStack *stack,DataType x)
{
 if(!StackFull(stack)){
  printf("Stack is full\n");
  return;
 }
 stack->top+=1;
 stack->data[stack->top]=x;
}
//从栈顶取出数据
DataType StackPop(SeqStack *stack)
{
 if(!StackEmpty(stack))
 {
  printf("Stack is Empty\n");
  return -1;
 }
 return stack->data[stack->top--];
}
//得到栈顶元素
DataType GetTop(SeqStack *stack)
{
 if(!StackEmpty(stack))
 {
  printf("Stack is Empty\n");
  return -1;
 }
 return stack->data[stack->top];
}
int main(void)
{
 SeqStack s;
 StackInit(&s);
 StackPush(&s,1);
 StackPush(&s,2);
 printf("%d\n",StackPop(&s));
 printf("%d\n",GetTop(&s));
 return 0;

}

2.栈的链表实现

栈的链表实现push和pop都是从头指针操作的,push即链表的插入操作是使用头插法。如果在函数中对传入的指针改变其地址,要使用双重指针,因为c中函数传参是传值。

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

typedef int DataType;
typedef struct stacknode{
 DataType data;
 struct stacknode *next;
}StackNode;
typedef StackNode *StackList;
int StackEmpty(StackList *top)
{
 return *top==NULL;
}
int StackPush(StackList *top,DataType x)
{
 StackList temp=malloc(sizeof(StackNode));
 if(temp==NULL)
  return -1;
 temp->data=x;
 //将新节点插入栈顶
 temp->next=*top;
 //将栈顶指针指向新元素
 *top=temp;
 return 0;
}
int StackPop(StackList *top)
{
 DataType inte=0;
 StackList temp=*top;
 if(StackEmpty(*top)){
  printf("Stack is empty\n");
  return -1;
 }
 inte=temp->data;
 printf("This is in StackPop,%d\n",inte);
 *top=temp->next;
 free(temp);
 return inte;
}
DataType GetTop(StackList top)
{
 if(StackEmpty(&top))
  return -1;
 return top->data;
}
int main(void)
{
 StackList s;
 StackPush(&s,1);
 StackPush(&s,2);
 printf("%d\n",StackPop(&s));
 printf("%d\n",GetTop(s));
 return 0;
}

 

原创粉丝点击