栈的链式存储 c实现的几种基本操作

来源:互联网 发布:狸猫网络助手安卓 编辑:程序博客网 时间:2024/06/05 23:16
 我们都知道单链表中的结尾有一个NULL,正好栈的链式实现中就是利用了这个特性,把NULL看成是栈的底部;然后呢,把进栈和出栈都是从栈顶指针开始的。正好利用了这样的特性,使得链式栈使用青来没有什么难度。

//
#include "stdafx.h"
#include <iostream>
using namespace std;

typedef struct Node
{
 int iData;
 Node* next;
}StackNode,*StackLink;


// 创建一个长度为n的链式栈
StackLink Creat(int n)
{
 cout << "请输入" << n << "个整数" << endl;
 int iNum = 0;
 StackLink p,r,top = NULL;
 for (int i = 0;i < n;++ i)
 {
  cin >> iNum;
  p = (StackLink)malloc(sizeof(StackNode));
  p->iData = iNum;
  p->next = NULL;
  if (top == NULL)
  {
   top = p;
  }
  else
  {
   r->next = p;
  }
  r = p;
 }
 return top;
  
}
// 出事化一个链式栈
void InitialStackList(StackLink& top)
{
 top = NULL;
}

// 测试一个栈是否为空;
int IsEmpty(StackLink& top)
{
 return top == NULL;
}

// 取当前栈顶元素;
void GetTopStack(StackLink& top,int& temp)
{
 if (IsEmpty(top))
 {
  throw"栈空";
 }
 else
 {
  temp = top->iData;
 }
}

// 栈中的进栈
int PushStack(StackLink& top,int item)
{
 StackLink p = NULL;
 if (!(p = (StackLink)malloc(sizeof(StackNode)) ))
 {
  return 0;  // 开辟失败,不能创建成功;
 }
 else
 {
  p->iData = item;
  p->next = top;
  top = p;
  return 1;   // 插入成功;
 }
}

// 出栈问题
int Pop(StackLink& top,int& iTemp)
{
 StackLink p = NULL;
 if (IsEmpty(top))
 {
  return 0;
 }
 else
 {
  p = top;
  iTemp = p->iData;
  top = p->next;
  free(p);
  return 1;     // 操作成功;
 }
 return 1;
}

// 输出栈中的元素;
void Print(StackLink& top)
{
 if (IsEmpty(top))
 {
  throw"栈空";
 }
 else
 { 
  while(top)
  {
   cout << top->iData;
   top = top->next;
  }
 }
 cout << endl;
}

int main(int argc,char* argv[])
{
 int iNumber = 5;
 StackLink top = NULL;
 top = Creat(iNumber);
 Print(top);
 InitialStackList(top);
 if (IsEmpty(top))
 {
  cout << "栈是空的!" << endl;
 }
 else
 {
  cout << "栈不是空的!"<< endl;
 }
 
 return 0;
}