栈
栈是一种特殊的线性表:
- 它只能在一端进行操作
- 先进后出,后进先出
注意:这里的实现是一种只使用头插法的单链表,可以叫做链栈,不是动态数组的栈
初始化栈
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node* next;
} Node;
Node* initList() {
Node* S = (Node*)malloc(sizeof(Node));
S -> data = 0;
S -> next = NULL;
return S;
}
int main()
{
Node* S = initList();
return 0;
}
入栈
void push(Node* S, int data) {
Node* n = (Node*)malloc(sizeof(Node));
n -> data = data;
n -> next = S -> next;
S -> next = n;
S -> data++;
}
出栈
int pop(Node* S) {
if (isEmpty(S)) {
return -1;
} else {
Node* p = S -> next;
int data = p -> data;
S -> next = p -> next;
S -> data--;
free(p);
return data;
}
}
判断栈空
int isEmpty(Node* S) {
if (S -> data == 0 || S -> next == NULL) {
return 1;
} else return 0;
}
遍历栈
void printStack(Node* S) {
Node* p = S -> next;
while(Node) {
printf("%d -> ",p -> data);
p = p -> data;
}
printf("NULL\n");
}