链栈:初始化、判断栈空、入栈、出栈、获取栈顶元素等

#include <stdio.h>
#include <stdlib.h>

#define TRUE 1
#define FALSE 0

typedef int ElementType;

typedef struct node {
    ElementType data;
    struct node *next;
}StackNode, *LinkStack;


/* 链栈的初始化 */
void InitStack(LinkStack top) {
    top->next = NULL;//top指针指向栈顶元素的上一个位置,下同
}


/* 判断栈是否为空 */
int IsEmpty(LinkStack top) {
    if(top->next == NULL) 
	   return TRUE;
    return FALSE;
}


/* 元素入栈 */
int Push(LinkStack top, ElementType element) {
    LinkStack temp;
    temp = (LinkStack)malloc(sizeof(StackNode));
    if(temp == NULL) 
	     return FALSE;
    temp->data = element;
    temp->next = top->next;
    top->next = temp;
    return TRUE;
}


/* 元素出栈 */
int Pop(LinkStack top, ElementType *element) {
    if(IsEmpty(top)) 
	    return FALSE;
    StackNode *temp = top->next;
    *element = temp->data;
    top->next = temp->next;
    free(temp);
    return TRUE;
}


/* 获取栈顶元素 */
int GetTop(LinkStack top, ElementType *element) {
    if(top->next == NULL)
        return FALSE;
    *element = top->next->data;
	return TRUE;
}



int main() 
{
    LinkStack s;
    int i;
    int result;
    s = (LinkStack)malloc(sizeof(StackNode));
    InitStack(s);
    for(i=1; i<=10; i++)
        Push(s,i);
        
    GetTop(s,&result);
	printf("栈顶元素为:%d\n",result);    
    
    
    printf("元素依次出栈:\n"); 
	while (!IsEmpty(s)) 
    {
        Pop(s,&result);
        printf("%d\n",result);
    }
} 
  • 10
    点赞
  • 54
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值