鏈棧的基本操作實現


1. 鏈棧含頭結點模型示意圖如下:

2. 鏈棧結構定義如下:

struct StackNode {
	int data;
	StackNode* next;
};

3. 鏈棧的基本操作函數如下:

  • StackNode* createStack(); // 創建棧頭結點
  • void Push(StackNode* head, int item); // 入棧
  • int Pop(StackNode* head); // 出棧,並返回出棧數據
  • int getStackLength(StackNode* head); // 獲取棧元素個數

4. 具體代碼實現如下:

#include <iostream>

using namespace std;

// 結點結構
struct StackNode {
	int data;
	StackNode* next;
};

// 創建棧頭結點
StackNode* createStack() {
	StackNode* head = (StackNode*)malloc(sizeof(StackNode));
	if (head == NULL) {
		cout << "Memory allocate failed." << endl;
		return NULL;
	}
	head->data = 0;
	head->next = NULL;
	return head;
}

// 入棧
void Push(StackNode* head, int item) {
	if (head == NULL) {
		return;
	}
	StackNode* node = (StackNode*)malloc(sizeof(StackNode));
	if (node == NULL) {
		cout << "Memory allocate failed." << endl;
		return;
	}
	node->data = item;
	node->next = head->next;
	head->next = node;
}

// 出棧
int Pop(StackNode* head) {
	if (head == NULL || head->next == NULL) {
		cout << "Error." << endl;
		return 0;
	}
	StackNode* node = (StackNode*)malloc(sizeof(StackNode));
	if (node == NULL) {
		cout << "Memory allocate failed." << endl;
		return 0;
	}
	StackNode* temp = head->next;
	head->next = temp->next;
	int val = temp->data;
	free(temp);
	return val;
}

// 獲取棧元素個數
int getStackLength(StackNode* head) {
	if (head == NULL || head->next == NULL) {
		return 0;
	}
	StackNode* p = head->next;
	int len = 0;
	while (p != NULL) {
		len++;
		p = p->next;
	}
	return len;
}

int main() {
	StackNode* head = NULL;
	head = createStack();
	Push(head, 5);
	Push(head, 4);
	Push(head, 3);
	cout << getStackLength(head) << endl;
	cout << Pop(head) << endl;
	cout << Pop(head) << endl;
	cout << getStackLength(head) << endl;
	cout << Pop(head) << endl;
	cout << getStackLength(head) << endl;
	system("pause");
	return 0;
}

5. 運行結果截圖如下:


免責聲明!

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



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