这一部分的算法和链表联系的比较紧密,只要链表弄明白了,相信栈的算法也不会太难理解的。。。
栈算法的代码如下:
//
// main.m
// 栈程序
//
// Created by 小伴 on 16/7/24.
// Copyright © 2016年 huangqimeng. All rights reserved.
//
#import <Foundation/Foundation.h>
#include <stdio.h>
#include <malloc/malloc.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node *pNext;
}NODE, *PNODE;
typedef struct Stack {
PNODE pTop;
PNODE pBottom;
}STACK, *PSTACK; //PSTACK等价于 struct STACK *
void initStack(PSTACK);
void pushStack(PSTACK, int);
void traverse(PSTACK);
bool popStack(PSTACK, int *);
void clearStack(PSTACK);
int main(int argc, const char * argv[]) {
@autoreleasepool {
STACK S; //STACK 等价于 struct Stack
int val;
initStack(&S);
pushStack(&S, 1);
pushStack(&S, 2);
pushStack(&S, 3);
pushStack(&S, 4);
pushStack(&S, 5);
traverse(&S);
if (popStack(&S, &val)) {
printf("出栈成功,出栈的元素为:%d\n", val);
} else {
printf("出栈失败\n");
}
traverse(&S);
clearStack(&S);
traverse(&S);
}
return 0;
}
/**
* 初始化一个空栈
*/
void initStack(PSTACK pS) {
pS->pTop = (PNODE)malloc(sizeof(NODE));
if (pS->pTop == NULL) {
printf("动态内存分配失败\n");
exit(-1);
} else {
pS->pBottom = pS->pTop;
pS->pTop->pNext = NULL; //pS->pBottom->pNext = NULL;
}
}
/**
* 压栈
*/
void pushStack(PSTACK pS, int val) {
PNODE pNew = (PNODE)malloc(sizeof(NODE));
pNew->data = val;
pNew->pNext = pS->pTop; //pS->pTop不能换作pS->pBottom
pS->pTop = pNew;
}
void traverse(PSTACK pS) {
PNODE p = pS->pTop;
while (p != pS->pBottom) {
printf("%d ", p->data);
p = p->pNext;
}
printf("\n");
}
bool empty(PSTACK pS) {
if (pS->pTop == pS->pBottom) {
return true;
} else {
return false;
}
}
/**
* 把pS指向的栈出栈一次,并把出栈的元素存入pVal形参所指向的变量中,如果出栈失败返回false,否则返回true
*/
bool popStack(PSTACK pS, int *pVal) {
if (empty(pS)) {//pS本身存放的就是S的地址
return false;
} else {
PNODE temp = pS->pTop;
*pVal = temp->data;
pS->pTop = temp->pNext;
free(temp);
temp = NULL;
return true;
}
}
//栈清空
void clearStack(PSTACK pS) {
if (!empty(pS)) {
PNODE p = pS->pTop;
PNODE q = NULL;
while (p != pS->pBottom) {
q = p->pNext;
free(p);
p = q;
}
pS->pTop = pS->pBottom;
}
}
网友评论