GitHub同步更新(已分类):Data_Structure_And_Algorithm-Review
公众号:URLeisure 的复习仓库
公众号二维码见文末
以下是本篇文章正文内容,下面案例可供参考。
顺序栈是分配一段连续的空间,需要两个指针,base指向栈底,top指向栈顶。
链栈每个节点的地址是不连续的,只需要一个栈顶指针即可。
从图中可以看出,链栈的每个节点都包含两个域:数据域和指针域。
首先定义一个结构体(内部类),包含一个数据域和一个指针域。
c++代码如下(示例):
typedef struct SNode {
int data;//数据域
SNode *next;//指针域
} *LinkStack;
java代码如下(示例):
public static class SNode {
int data;
SNode next;
}
c++代码如下(示例):
void Init(LinkStack &S) {
S = NULL;
}
java代码如下(示例):
public static void init(SNode s){
s = new SNode();
}
c++代码如下(示例):
void Push(LinkStack &S, int e){
LinkStack p = new SNode;
p->data = e;
p->next = S;//新元素的下个地址是老的栈顶
S = p;//栈顶上移
}
java代码如下(示例):
public static void push(int e) {
SNode p = new SNode();
p.data = e;
p.next = s;
s = p;
}
c++代码如下(示例):
bool Pop(LinkStack &S, int &e){
if(S == NULL){//栈空
return false;
}
LinkStack p = S;//临时节点
S = p->next;//栈顶下移
e = p->data;//记录出栈元素
delete p;//释放空间
return true;
}
java代码如下(示例):
public static int pop() {
if (s == null) {
return -1;
}
SNode p = s;
s = s.next;
return p.data;
}
c++代码如下(示例):
int GetTop(LinkStack S){
if(S == NULL){
return -1;
}
return S->data;
}
java代码如下(示例):
public static int getTop() {
if (s == null) {
return -1;
}
return s.data;
}
c++代码如下(示例):
#include
using namespace std;
typedef struct SNode {
int data;
SNode *next;
} *LinkStack;
void Init(LinkStack &S) {
S = NULL;
}
void Push(LinkStack &S, int e) {
LinkStack p = new SNode;
p->data = e;
p->next = S;
S = p;
}
bool Pop(LinkStack &S, int &e) {
if (S == NULL) {
return false;
}
LinkStack p = S;
S = p->next;
e = p->data;
delete p;
return true;
}
int GetTop(LinkStack S) {
if (S == NULL) {
return -1;
}
return S->data;
}
int main() {
LinkStack S;
int n, e;
Init(S);
cout << "链栈初始化成功" << endl;
cout << "输入元素个数:" << endl;
cin >> n;
cout << "输入元素,依次入栈" << endl;
while (n--) {
cin >> e;
Push(S, e);
}
cout << "元素依次出栈!" << endl;
while (S != NULL) {
cout << GetTop(S) << " ";
Pop(S, e);
}
cout << endl;
}
java代码如下(示例):
public class A {
public static class SNode {
int data;
SNode next;
}
private static SNode s;
public static void init(SNode s){
s = new SNode();
}
public static void push(int e) {
SNode p = new SNode();
p.data = e;
p.next = s;
s = p;
}
public static int pop() {
if (s == null) {
return -1;
}
SNode p = s;
s = s.next;
return p.data;
}
public static int getTop() {
if (s == null) {
return -1;
}
return s.data;
}
public static void main(String[] args) {
init(s);
System.out.println("链栈初始化成功!");
push(5);
push(4);
push(3);
push(2);
push(1);
System.out.println("创建成功");
System.out.println("元素依次出栈");
while (s != null) {
System.out.print(getTop() + " ");
pop();
}
System.out.println();
}
}
在实际应用中,顺序栈比链栈应用更广泛。
下期预告: 循环队列