栈的实现

栈的基本操作有Push(入栈)和Pop(出栈),前者相当于插入,后者相当于删除最后插入的元素,两个都是在栈顶进行操作的。栈也叫做LIFO(后入先出)表。

对于栈的实现既可以使用链表,也可以使用数组,本文采用的是链表栈。

首先,是定义结构体

struct Node_s;
typedef struct Node_s *PtrToNode;
typedef PtrToNode Stack;

struct Node_s
{
    ElementType Element;
    PtrToNode Next;
};

下面是入栈和出栈的具体实现,S作为头结点,始终指向top元素,新入栈的元素放在S后面,出栈的元素也是删除S后面的那个元素。

/*检查栈是否为空*/
int IsEmpty_s( Stack S )
{
    return S->Next == NULL;
}
/*创建一个栈*/
Stack CreateStack( void )
{
    Stack S = (Stack)malloc(sizeof(struct Node_s));
    if(S == NULL)
        printf("out of space!");
    S->Next = NULL;
    return S;
}
/*入栈操作*/
void Push( ElementType X,Stack S )
{
    Stack newer = (Stack)malloc(sizeof(struct Node_s));
    newer->Element=X;
    newer->Next=S->Next;
    S->Next = newer;
}
/*返回最顶端的元素*/
ElementType Top( Stack S )
{
    if(S->Next != NULL)
        return S->Next->Element;
    printf("stack is empty!");
    return NULL;
}
/*出栈操作*/
void Pop( Stack S )
{
    Stack tmp;
    tmp = S->Next;
    S->Next = S->Next->Next;
    free(tmp);
}

 

posted @ 2016-08-13 22:50  九杯水  阅读(156)  评论(0)    收藏  举报