您的位置:首页 > 编程语言 > C语言/C++

算法学习 - 栈的链表实现(C++)

2014-07-28 00:54 405 查看
栈是用的很多的一个数据结构,这里写用链表实现的方法。

栈是先进后出,能解决很多问题,例如:括号匹配,后缀表达式等。

也可以用数组来实现~ 数组的话比较简单,也可以用链表游标~

下面贴代码,基本操作比较少。

//
//  main.cpp
//  Stack
//
//  Created by Alps on 14-7-27.
//  Copyright (c) 2014年 chen. All rights reserved.
//

#include <iostream>

using namespace std;

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

struct Node{
int X;
PtrToNode Next;
};

int isEmpty(Stack S){
return S->Next == NULL;
}

Stack createStack(void){
Stack S;
S = (Stack)malloc(sizeof(Node));
S->Next = NULL;
return S;
}

void Push(Stack S, int X){
Stack element;
element = (Stack)malloc(sizeof(Node));
element->X = X;
element->Next = S->Next;
S->Next = element;
}

void Pop(Stack S){
if (!isEmpty(S)) {
Stack tmp = S->Next;
S->Next = tmp->Next;
free(tmp);
}else{
printf("Empty stack can't pop cell\n");
}
}

int Top(Stack S){
int X;
if (!isEmpty(S)) {
return X = S->Next->X;
}else{
printf("empty stack, no top cell\n");
}
return 0;
}

void makeEmpty(Stack S){
if (S == NULL) {
printf("create stack first\n");
}
while (!isEmpty(S)) {
Pop(S);
}
}

int main(int argc, const char * argv[])
{
Stack S = createStack();
Push(S, 2);
Push(S, 4);
Push(S, 6);
Push(S, 8);
printf("%d\n",Top(S));
Pop(S);
printf("%d\n",Top(S));
makeEmpty(S);
printf("%d\n",Top(S));
return 0;
}


下次写栈解决的括号匹配问题和后缀表达式的求解~
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  算法 C++