C++数据结构
把链栈想象成单链表头结点的后插和后删操作
不带头结点的链栈
//不带头结点的链栈
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
typedef struct Linknode1 {
int data;
struct Linknode1* next;
}*LiStack1;
void InitStack1(LiStack1& L) {
L= NULL;
}
//进栈
LiStack1 Push1(LiStack1& L, int x) {
Linknode1* s = (LiStack1)malloc(sizeof(Linknode1));
s->data = x;
s->next = L;
L= s;
return L;
}
//出栈
bool Pop1(LiStack1 & L) {
if (L == NULL) {
return false;
}
L = L->next;
printf("-------------------------");
return true;
}
//读栈
void Gettop1(LiStack1 L) {
while (L) {
printf("%d", L->data);
L = L->next;
}
printf("\n");
}
int main()
{
LiStack1 L;
InitStack1(L);
L = Push1(L, 2);
L = Push1(L, 8);
L = Push1(L, 9);
L = Push1(L, 6);
L = Push1(L, 4);
Gettop1(L);
Pop1(L);
Pop1(L);
Pop1(L);
Gettop1(L);
return 0;
}
结果:
带头结点的链栈
//带头结点的链栈
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
//带头结点
typedef struct Linknode {
int data;
struct Linknode* next;
}*LiStack;
bool InitStack(LiStack &L) {
L = (LiStack)malloc(sizeof(Linknode));
if (L == NULL) {
return false;
}
L->next=NULL;
return true;
}
//进栈
LiStack Push(LiStack &L, int x) {
Linknode *s = (LiStack)malloc(sizeof(Linknode));
s->data = x;
s->next = L->next;
L->next = s;
return L;
}
//出栈
bool Pop(LiStack& L) {
if (L->next == NULL) {
return false;
}
Linknode *q=L->next;
L->next= q->next;
printf("-------------------------");
return true;
}
//读栈
void Gettop(LiStack L) {
while (L->next) {
L = L->next;
printf("%d", L->data);
}
printf("\n");
}
int main()
{
LiStack L;
InitStack(L);
L=Push(L, 2);
L = Push(L, 8);
L = Push(L, 9);
L = Push(L, 6);
L = Push(L, 4);
Gettop(L);
Pop(L);
Pop(L);
Pop(L);
Gettop(L);
return 0;
}
结果: