注册 登录  
 加关注
   显示下一条  |  关闭
温馨提示!由于新浪微博认证机制调整,您的新浪微博帐号绑定已过期,请重新绑定!立即重新绑定新浪微博》  |  关闭

Aspirer's blog

停止维护,新博客地址:http://aspirer.wang/

 
 
 

日志

 
 

  

2009-08-16 10:48:10|  分类: 学习心得 |  标签: |举报 |字号 订阅

  下载LOFTER 我的照片书  |

栈 - aspirer - Aspirers blog

#include
#include

using namespace std;

typedef struct node
{
 int data;
 struct node *next;
}Node;

typedef struct stack
{
 Node *bottom;
 Node *top;
}Stack;

Stack *Push(Stack *st, int d)
{
 Node *tmp = NULL;
 if (NULL == st)
 { 
  cerr << "Error, stack is NULL!" << endl;
  return NULL;
  }
 
 tmp = (Node *)malloc(sizeof(Node));
 if (NULL == tmp)
 {
  cerr << "memory allocation error!" << endl;
   return NULL;
 }
 tmp->data = d;
 tmp->next = NULL;

 if (NULL == st->bottom)
 {
  st->bottom = tmp;
  st->top = tmp;
 }
 else
 {
  st->top->next = tmp;
  st->top = tmp;
 }
 return st;
}

void Free(Stack *st)
{
 Node *tmp = NULL;
 if (NULL == st)
 {
  return;
 }
 while (st->bottom != NULL)
 {
  tmp = st->bottom;
  st->bottom = tmp->next;
  cout << tmp->data << " was freed." << endl;
  free(tmp);
 }
 cout << "stack was freed." << endl;
 
}

Node *Pop(Stack *st)
{
 Node *tmp;
 if (NULL == st)
 {
  return NULL;
 }
 if (NULL == st->bottom)
 {
  return NULL;
 }
 else if (st->bottom == st->top)
 {
  tmp = st->bottom;
  st->bottom = NULL;
  st->top = NULL;
  return tmp;
 }
 else
 {
  tmp = st->bottom;
  while (tmp->next != st->top)
  {
   tmp = tmp->next;
  }
  st->top = tmp;  
  tmp = tmp->next;
  st->top->next = NULL;
  return tmp;
 }
}

int Len(Stack *st)
{
 Node *p;
 int len = 0;
 if (NULL == st)
 {
  return len;
 }
 if (NULL == st->bottom)
 {
  return len;
 }

 p = st->bottom;
 while (p != NULL)
 {
  p = p->next;
  len++;
 }
 return len;
}

void Print(Stack *st)
{
 Node *p;
 //int len = 0;
 if (NULL == st)
 {
  cout << "stack is NULL." << endl;
  return ;
 }
 if (NULL == st->bottom)
 {
  cout << "stack is NULL." << endl;
  return ;
 }

 p = st->bottom;
 while (p != NULL)
 {
  cout << p->data;
  p = p->next;
  if (p != NULL)
  {
   cout << "-->";
  }
 }
 cout << endl;
}

int main()
{
 Stack *st = new Stack();//(Stack *)malloc(sizeof(Stack));
 Node *nd;
 //st->bottom = NULL;
 //st->top = NULL;
 for (int i = 1; i < 5; ++i)
 {
  Push(st, i);
  cout << i << " was pushed in stack." << endl;
 }

 cout << "Stack length = " << Len(st) << endl;
 Print(st);

 for (int i = 1; i < 6; ++i)
 {
  nd = Pop(st);
  if (nd != NULL)
  {
   cout << nd->data << " was poped." << endl;
  }
  free(nd);
 }
 //Free(st);
 //free(st);
 delete []st;
 return 0;
}

 

  评论这张
 
阅读(368)| 评论(0)
推荐 转载

历史上的今天

在LOFTER的更多文章

评论

<#--最新日志,群博日志--> <#--推荐日志--> <#--引用记录--> <#--博主推荐--> <#--随机阅读--> <#--首页推荐--> <#--历史上的今天--> <#--被推荐日志--> <#--上一篇,下一篇--> <#-- 热度 --> <#-- 网易新闻广告 --> <#--右边模块结构--> <#--评论模块结构--> <#--引用模块结构--> <#--博主发起的投票-->
 
 
 
 
 
 
 
 
 
 
 
 
 
 

页脚

网易公司版权所有 ©1997-2018