思路:s指向第一个进栈的元素,其余的按头插法插入 另一个刚刚想到 假设栈顶指针为top 初始化为null 插入节点x的操作应该是 x-next=top top =x
#include <iostream>
#include <stdlib.h>
using namespace std;
typedef struct LinkNode {
int data;
struct LinkNode *next;
}*LinkStack;
void init(LinkStack &s);
void push(LinkStack &s, int x);
void pop(LinkStack &s, int &e);
int getTop(LinkStack s);
void Destory(LinkStack &s);
int main(void) {
LinkStack s;
init(s);
push(s,1);
push(s,2);
push(s,3);
cout << "main:" << getTop(s) << endl;
Destory(s);
getTop(s);
}
void init(LinkStack &s) {
s = NULL;
}
void push(LinkStack &s, int x) {
LinkNode *t = (LinkNode*)malloc(sizeof(LinkNode));
t->data = x;
if (s == NULL) {
t->next = NULL;
s = t;
}
else {
t->next = s->next;
s->next = t;
}
}
void pop(LinkStack &s, int &e) {
if (s == NULL) {
printf("栈空\n");
return;
}
if (s->next == NULL) {
e = s->data;
s = NULL;
return;
}
LinkNode *t = s->next;
e = t->data;
s->next = t->next;
free(t);
}
int getTop(LinkStack s) {
if (s == NULL) {
printf("栈空!\n");
exit(0);
}
if (s->next == NULL) return s->data;
return s->next->data;
}
void Destory(LinkStack &s) {
if (s == NULL) {
printf("栈已经空了!\n");
exit(0);
}
LinkNode *t;
while(s->next != NULL) {
t = s->next;
s->next = t->next;
free(t);
}
t = s;
free(t);
s = NULL;
}
|