• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录

尼古拉斯豆

  • 博客园
  • 联系
  • 订阅
  • 管理

公告

View Post

数据结构--栈--链式存储

栈的链式存储跟线性表的链式存储一样,只是添加删除数据的方式不同。

编译器:GCC

#include <stdio.h>

typedef int elemType;

struct sNode{
    elemType data;
    struct sNode *next;
};

/* 1.初始化栈为空*/
void initStack(struct sNode **hs)
{
    *hs = NULL;
    return;
} 

/* 2.向链中插入一个元素(入栈) */
void push(struct sNode **hs, elemType x)
{
    struct sNode *temp;
    temp = (struct sNode *)malloc(sizeof(struct sNode));
    if(temp == NULL)
    {
        printf("空间申请失败...\n");
        system("pause"); 
    }
    temp->next = *hs;
    temp->data = x;
    *hs = temp;

    return;
}
/* 3.从链栈中删除一个元素并返回它(出栈)*/
elemType pop(struct sNode **hs)
{
    if(*hs == NULL)
    {
        printf("栈空,出栈失败...\n");
        system("pause"); 
    }
    struct sNode *temp;
    elemType data = (*hs)->data;

    temp = *hs;
    *hs= (*hs)->next;
    free(temp);
    
    return data; 
}
/* 4.读取栈顶元素*/
elemType peek(struct sNode **hs)
{
    if(*hs == NULL)
    {
        printf("栈空,出栈失败...\n");
        return -1; 
    }
    return (*hs)->data;
}
/* 5.判断链栈是否为空,为空返回1,否则返回0*/
int emptyStack(struct sNode **hs)
{
    if(*hs == NULL)
    {
        return 1; 
    }else{
        return 0;
    }
}
/* 6.清除链栈为空*/
void clearStack(struct sNode **hs)
{
    while(*hs != NULL)
    {
        pop(hs);
    }
    return;
}


/*******************************************************/
int main(void)
{
    struct sNode *s;
    int a[8] = {3,8,5,17,9,30,15,22};
    int i;
    
    initStack(&s);
    printf("初始化栈...\n");
    for(i=0; i<8; i++)
    {
        printf("%d ",a[i]);
        push(&s, a[i]);     
    }
    
    printf("\n操作顺序:pop pop push(68) pop pop \n");
    printf("%d ",pop(&s));
    printf("%d ",pop(&s));
    push(&s, 68);
    printf("%d ",pop(&s));
    printf("%d ",pop(&s));
    printf("\npop出剩余的...\n");
    while(!emptyStack(&s))
    {
        printf("%d ", pop(&s));
    }
    printf("\n");
    clearStack(&s);
    
    system("pause");
    return 0;    
}

 

************************************************************************

运行结果:

************************************************************************

初始化栈...
3 8 5 17 9 30 15 22
操作顺序:pop pop push(68) pop pop
22 15 68 30
pop出剩余的...
9 17 5 8 3
请按任意键继续. . .

posted on 2012-07-02 15:35  尼古拉斯豆  阅读(197)  评论(0)    收藏  举报

刷新页面返回顶部
 
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3