Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- using namespace std;
- class Stack {
- private:
- class Node { // hnútur sem geymir heiltölugögn og vísun í næsta hnút
- public:
- int data;
- Node* next;
- Node(int data, Node* next) {
- this->data = data;
- this->next = next;
- }
- };
- Node* head;
- int lengd;
- public:
- Stack() { // smiður fyrir tóman stack
- this->head = nullptr;
- this->lengd = 0;
- }
- ~Stack() { delete this->head; } // eyðum halanum
- void push(int n) { // búum til hnút með gögnunum og setjum hann sem hausinn:
- Node* p = new Node(n, this->head);
- this->head = p;
- this->lengd++;
- }
- int pop() { // skilum efsta gildinu og eyðum því:
- if (this->head == nullptr) {
- throw underflow_error("Reynt var að fjarlægja efsta stak af tómum hlaða");
- } else {
- int skilagildi = this->head->data;
- // stillum næsta stak sem haus og eyðum hausnum:
- Node* temp = this->head;
- this->head = this->head->next;
- delete temp;
- this->lengd--;
- return skilagildi;
- }
- }
- int peek() { // skilum efsta gildinu, eyðum því ekki:
- if (this->head == nullptr) {
- throw underflow_error("Reynt var að kíkja á efsta stak tóms hlaða");
- } else return this->head->data;
- }
- bool isEmpty() { // skoðum hvort hlaðinn sé tómur:
- if (this->head == nullptr) return true;
- else return false;
- }
- };
- int main() {
- Stack s;
- cout << "Setjum tölurnar 1, 2 og 4 á hlaðann s." << endl;
- s.push(1);
- s.push(2);
- s.push(4);
- cout << "Stelum efsta stakinu, " << s.pop() << ", af s." << endl;
- cout << "Setjum tölurnar 8, 16 og 32 á s." << endl;
- s.push(8);
- s.push(16);
- s.push(32);
- cout << "Kíkjum á efsta stak s, það er " << s.peek() << "." << endl;
- cout << "Fjarlægjum nú tölurnar af s: " << endl;
- while (!s.isEmpty()) {
- cout << s.pop() << " ";
- }
- cout << endl;
- try {
- s.peek();
- } catch (underflow_error e) {
- cout << "Ekki tókst að kíkja á s, enda tómur" << endl;
- }
- try {
- s.pop();
- } catch (underflow_error e) {
- cout << "Ekki tókst að fjarlægja stak af s, enda tómur" << endl;
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment