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

数据结构:堆栈的链式存储实现

2015-04-13 14:14 489 查看
栈的链式存储实际是一个单链表,叫做栈链。插入和删除应该都只在栈链的栈顶进行。

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

struct Node;
typedef struct Node * PtrToNode;
typedef PtrToNode Stack;

struct Node{
    ElementType element;
    PtrToNode Next;
};

//创建栈
Stack createStack(){
    Stack s;
    s = (PtrToNode)malloc(sizeof(PtrToNode));
    if(s == NULL){
        printf("fail");
        s->Next = NULL;
    }
}

//检测栈是否为空
int isEmpty(Stack s){
    return s->Next == NULL;
}

//使栈为空
void makeEmpty(Stack s){
    Stack p,temp;
    p = s->Next;
    s->Next = NULL;
    while(p!=NULL){
        temp = p->Next;
        free(p);
        p = temp;
    }
}

//入栈
void Push(ElementType ele,Stack s){
    Stack tempCell;
    tempCell = (PtrToNode)malloc(sizeof(PtrToNode));
    if(tempCell == NULL){
        tempCell->element = ele;
        tempCell->Next = s->Next;
        s->Next = tempCell;
    }
}

//返回栈顶元素的值
ElementType Top(Stack s){
    if(!isEmpty(s)){
        return s->Next->element;
    }else{
        Error("Empty Stack\n");
        return 0;
    }
}

//出栈
void Pop(Stack s){
    Stack firstCell;
    if(!isEmpty(s)){
        firstCell = s->Next;
        s->Next = s->Next->Next;
        free(firstCell);
    }else{
        Error("Empty");
    }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: