链栈的基本操作

/*
 * 链栈的实现
 */
#include <stdio.h>
#include<stdlib.h>


//用一个带头结点的单链表来表示栈
typedef struct Node{
    int data;
    struct Node *next;
}Node;

//另外定义一个结构体来保存链表的头结点,并将其作为栈顶
typedef struct stack{
   Node *top;  //头指针
   int count;
}Stack;
//另外定义一个结构体来保存链表的头结点,并将其作为栈顶

/*栈的初始化*/
Stack init(Stack s)
{

 s.top = (Node *)malloc(sizeof(Node));//制造一个头结点
 s.top->next = NULL;

 return s;
}

//top相当于链表的头指针,每次插入用的头插法
//链表的头部是栈顶尾部是栈底
void push(Stack s,int x)
{ 

 Node *p;
    p=(Node *)malloc(sizeof(Node));

 p->next=NULL;
 p->data=x;

 p->next=s.top->next;
 s.top->next=p;

} 

int pop(Stack s)
{

  Node *p=NULL;
  int x;
  x = s.top->next->data;

  p = s.top->next;
  s.top->next = p->next; 
  free(p);

  return(x);
}

int isempty(Stack s)
{
  if(s.top->next==NULL) return 1;
  else  return 0;
}

int show(Stack s)
{
  Node *p;
  for(p=s.top->next;p!=NULL;p=p->next){
      printf("%4d",p->data);
     }
}

int main()
{
  //把单链表的头结点用s.top表示其他与链表一样
  Stack s;
  s = init(s);
  push(s,1);
  push(s,3);
  push(s,5);
  push(s,7);
  push(s,9);
  printf("\npush 1,3,5,7,9后:\n");
  show(s);
  pop(s);
  printf("\n指行一次pop:\n");
  show(s);
  pop(s);
  printf("\n再执行一次pop:\n");
  show(s);
  printf("\npush 2:\n");
  push(s,2);
  show(s);
  printf("\npush 4:\n");
  push(s,4);
  show(s);

}

猜你喜欢

转载自blog.csdn.net/zuiziyoudexiao/article/details/80424585