栈的笔记(3)--链栈

链栈:采用链表作为储存结构的栈,为操作方便,一般采用带头结点的单链表。
      链表的表头指针作为栈顶指针
链栈的结构定义如下:
typedef struct node
{
  StackElementType data;
  stuct node *next;

}LinkStackNode;
typedef LinkStackNode *LinkStack;

链栈进栈操作
int Push(LinkStack top,StackElementType x)
{
  LinkStackNode *temp;
  temp=(LinkStackNode *)malloc(sizeof(LinkstackNode));
  if(temp==NULL)
   return(FALSE);//申请空间失败
  temp->data=x;
  temp->next=top->next;
  top->next=temp;//修改当前栈顶元素
  return(TRUE);
}

链栈出栈操作
int Pop(LinkStack top,StackElementType *x)
{
  LinkStackNode *temp;
  temp=top->next;
  if(temp==NULL)
   return(FALSE);//栈为空
  top->next=temp->next;
  *x=temp->data;
  free(temp);//释放存储空间
  return(TRUE);
}

运用多个单链表,可以实现多个链栈(将多个链栈的栈顶指针放到一个一维指针数组中统一管理)

定义结构入如下:
#define M 10  //假设定义10个链栈
typedef stuct node
{
  StackElementType data;
  struct node *next;
}LinkStackNode *LinkStack;
linkStack top[M];
第i号的进栈操作
int pushi(LinkStack top[M],int i,StackElementType x)
{
  LinkStackNode *temp;
  temp=(LinkStackNode *)malloc(sizeof(LinkStackNode));
  if(temp==NULL)
   return(FALSE);
  temp->data=x;
  temp->next=top[i]->next;
  top[i]->next=temp;
  return(TRUE);
}

第i号栈元素的出栈操作
int Pop(LinkStack top[M],int i,StackElementType *x)
{
  LinkStackNode *temp;
  temp=top[i]->next;
  if(temp==NULL)
   return(FALSE);
  top[i]->next=temp->next;
  *x=temp->data;
  free(temp); //释放存储空间
  return(TRUE);
}

原文地址:https://www.cnblogs.com/chen521/p/4104319.html