您的位置:首页 > 理论基础 > 数据结构算法

喜羊羊系列之数据结构栈链

2015-04-11 13:02 127 查看
博客地址:http://blog.csdn.net/muyang_ren

栈链数据链接示意图



top为指向最后的节点的指针,栈头为一个NULL空地址,栈头也不存数据
1、头文件

head.h

#ifndef __linkstack_H__
#define __linkstack_H__

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

typedef int datatype;
typedef struct node{
    datatype data;
    struct node *next;
}linkstack, *linkstack_p;

extern void linkstack_add(linkstack_p *, int ); //入栈
extern void linkstack_init(linkstack_p * );//初始化表头
extern void linkstack_out(linkstack_p *,int *);//出栈
extern int top_empty(const linkstack_p);//判断地址是否为空
#endif


2、栈链实现函数

linkstack.c

#include "head.h"

//设置栈表头为null
void linkstack_init(linkstack_p *top){
    *top=NULL;
}

//开辟新的节点
void linkstack_new(linkstack_p *new){
    
    *new=(linkstack_p)malloc(sizeof(linkstack));
    if(NULL == *new){
        perror("malloc\n");
        exit(-1);
    }
}

//入栈
void linkstack_add(linkstack_p *top , int n){
    
    linkstack_p new;
    linkstack_new(&new);
    
    new->data = n;
    
    //入栈
    new->next=*top;
    *top = new;
}

//栈为空
int top_empty(const linkstack_p top){
    if(top==NULL)
        return 0;
    else
        return 1;
}

//出栈
void linkstack_out(linkstack_p *top, int *num){
    
    linkstack_p p;
    p=*top;

    *num = (*top)->data;  //将栈中最后进的数据放进num的地址
    *top = (*top)->next;
    free(p);
}


3、实现功能函数

main.c

#include "head.h"
//实现 10 进制数转换成 8 进制数

int main(void)
{
    int num, n;
    char *ch="0";
    linkstack_p top;

    linkstack_init(&top);              //初始化双向链表
    
    printf("输入十进数:");
    scanf("%d",&num);
    if(num<0)
    {
        ch="-0";
        num = -num;
    }
    
    while(num!=0){
        linkstack_add(&top,num%8);
        num=num/8;
    }
    
    printf("八进制数为: %s",ch);
    
    while(top_empty(top)){
        linkstack_out(&top,&n);
        printf("%d",n);
    }
    printf("\n");

    return 0;
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: