帶頭結點和不帶頭結點的鏈棧基本操作



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;
}

結果:
在這里插入圖片描述


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM