码迷,mamicode.com
首页 > 其他好文 > 详细

链表模拟堆栈

时间:2015-04-14 09:42:33      阅读:135      评论:0      收藏:0      [点我收藏+]

标签:

#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
typedef struct stack
{
 int data;
 struct stack *next;
}STACK;
STACK *head,*pr;
int nodeNum = 0;
STACK *Createnote(int num);
STACK *PushStack(int num);
int PopStack(void);
int main()
{
 int pushNum[5] = {111,222,333,444,555},popNum[5],i;
 for(i = 0;i < 5;i++)
 {
  PushStack(pushNum[i]);
  printf_s("Push %dth Data: %d\n",i+1,pushNum[i]);
 }
 for(i = 0;i < 5;i++)
 {
  popNum[i] = PopStack();
  printf_s("Pop %dth Data: %d\n",5-i,popNum[i]);
 }
 system("pause");
 return 0;
}
STACK *CreateNode(int num)
{
 STACK *p;
 p = (STACK *)malloc(sizeof(STACK));
 if(p == NULL)
 {
  printf_s("No enough memory!\n");
  exit(0);
 }
 p ->next = NULL;
 p ->data = num;
 return p;
}
STACK *PushStack(int num)
{
 if(nodeNum == 0)
 {
  head = CreateNode(num);
        pr = head;
  nodeNum++;
 }
 else
 {
  pr ->next = CreateNode(num);
  pr = pr ->next;
  nodeNum++;
 }
 return pr;
}
int PopStack(void)
{
 STACK *p = head;
 int result;
 for(;;)
 {
  if(p ->next ==NULL)
  {
   break;
  }
  else
  {
   pr = p;
   p = p->next;
   nodeNum--;
  }
 }
 pr ->next = NULL;
 result = p ->data;
 free(p);
 return result;
}

链表模拟堆栈

标签:

原文地址:http://www.cnblogs.com/joyclub/p/4423949.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!