栈:是一种后进先出(LIFO)的结构,对其插入删除只能在栈顶进行;
链表实现
- 节点:
#include<stdio.h> #include<stdlib.h> typedef struct Node *PtrToNode; typedef PtrToNode Stack; struct Node{ int Element; struct Node *Next; }
- 进栈(push):
void Push(int x,Stack s) { PtrToNode p; p = (PtrToNode)malloc(sizeof(struct Node)); if(p==NULL) printf("out of space!\n"); else { p->Element = x; p->Next = s->Next; s->Next = p; } }
- 返回栈顶元素(TOP):
int Top(Stack s) { if(s->Next!=NULL) return s->Next->Element; }
- 出栈(POP):
void Pop(stack s) { PtrToNode tmp; if(s->Next!=NULL) { tmp = s->Next; s->Next = tmp->Next; free(tmp); } else printf("The stack is empty!\n"); }
时间: 2024-11-06 22:40:04