【数据结构】顺序栈、链栈学习笔记

用顺序结构、链式结构实现了栈的数据结构。

  操作系统:Ubuntu 11.10

  编辑器:vim

  编译器:gcc

  调试器:gdb

顺序栈:

 

#include<stdio.h>
#include<malloc.h>
#define StackSize 10000

typedef struct _Stack
{
 int dat[StackSize];//开辟栈的内存空间
 int top;//指示栈顶位置
}Stack;

/*函数名:initStack*/
/*功能:初始化栈,置栈顶指针为-1*/
/*输入:栈名*/
/*输出:无*/
void initStack(Stack *S)
{
 S->top=-1;
}

/*函数名:push*/
/*功能:将数据压入栈中*/
/*输入:栈名、数据*/
/*输出:无*/
int push(Stack *S,int x)
{
 if(S->top==StackSize-1)
  return 1;
 else
  S->top++;//修改栈顶
  S->dat[S->top]=x;//给栈顶赋值
   return 0;
}

/*函数名:pop*/
/*功能:将数据弹出栈*/
/*输入:栈名*/
/*输出:弹出的数据*/
int pop(Stack *S)
{
 int x=0;
 if(S->top==-1)return 0;
 else
 {
  x=S->dat[S->top];//取数据
  S->top--;
  return x;
 }
}

/*函数名:main*/
/*功能:将数据弹压栈并弹出*/
/*输入:一连串的数据*/
/*输出:反序的数据*/
int main()
{
 int x=0;
 Stack S;
 initStack(&S);//初始化栈
 int temp=0;
 while(scanf("%d",&temp)&&temp)
 { 
   printf("%d ",temp);
   push(&S,temp);//将数据压入栈中
 }
 printf("\n");
 while(x=pop(&S))//将数据从栈中弹出
  printf("%d ",x);
  printf("\n");
 return 0;
}

测试:

  输入: 1 2 3 4 0

  输出:4 3 2 1

链栈:

#include<stdio.h>
#include<malloc.h>
typedef struct _stack
{
 int data;//数据域
 struct _stack *next;//指针域
}stack;

/*函数名:push*/
/*功能:将数据压入栈中*/
/*输入:栈名、数据*/
/*输出:无*/
int push(stack *S,int x)
{
 stack *temp;
 temp=(stack *)malloc(sizeof(stack));//为temp动态分配空间,数据类型为stack *型
 if(temp==NULL)
 	return 0;
 temp->data=x;
 temp->next=S->next;//注意S->next是否存在
 S->next=temp;//实现新节点的插入
 return 1;
}

/*函数名:pop*/
/*功能:将数据弹出栈*/
/*输入:栈名*/
/*输出:弹出的数据*/
int pop(stack *S)
{
 stack *temp;
 int x=0;
 if(S->next==NULL)
	return 0;
 else
 	temp=S->next;//注意S->next是否存在
 S->next=temp->next;//指向上一个节点
 x=temp->data;//取数据
 free(temp);
 return x;
}

/*函数名:main*/
/*功能:将数据弹压栈并弹出*/
/*输入:一连串的数据*/
/*输出:反序的数据*/
int main()
{
 stack *S;
 int c=1;
 int temp;
 S=(stack *)malloc(sizeof(stack));//为S动态分配空间
 S->next=NULL;//指定S->next为NULL
 /*数据不断压入堆栈直到输入数据为0*/
 while(scanf("%d",&c)&&c)
 {
 	push(S,c);
 	printf("%d ",c);
 }
 printf("\n");
 /*数据弹出堆栈*/
 while(temp=pop(S))
 	printf("%d ",temp);
 printf("\n");
 return 1;
}


测试数据:

 输入: 1 2 3 4 0

 输出:4 3 2 1



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值