Cài đặt Stack sử dụng Linked List
user_1746670
c_cpp
10 days ago
946 B
1
Indexable
Never
#include <bits/stdc++.h> using namespace std; struct Stack { int data; Stack* next; Stack() : data(0), next(nullptr) {} Stack(int val) : data(val), next(nullptr) {} }; void Push(Stack*& head, int x) { Stack* newNode = new Stack(x); newNode->next = head; head = newNode; } int Top(Stack* head) { return head->data; } void Pop(Stack*& head) { Stack* del = head; head = head->next; delete del; } void Print(Stack* head) { Stack* curr = head; while (curr != nullptr) { cout << curr->data << "->"; curr = curr->next; } cout << endl; } int main() { Stack* st = new Stack(6); Push(st, 4); Push(st, 7); Push(st, 3); Push(st, 5); Push(st, 9); Print(st); Pop(st); Print(st); int top = Top(st); cout << top << endl; Pop(st); Print(st); return 0; }
Leave a Comment