I am not experienced in C++, and wrote the below code for implementing a stack data structure using a linked list.
Can you please point out any flaws, errors, stupid mistakes, general improvements etc that can make this code better? Thanks.
#include <iostream>
using namespace std;
struct Node;
struct Node {
int data;
Node* next;
};
class Stack {
public:
Node* first;
Node* last;
Stack() {
first = 0;
last = 0;
}
~Stack() {
while (first != 0) { pop(); }
}
Stack& push(int value) {
Node* temp = new Node;
temp->data = value;
temp->next = 0;
if (first == 0) {
first = temp;
last = temp;
} else {
last->next = temp;
last = last->next;
}
cout << "Pushed " << value << " on the stack\n";
temp = 0;
return *this;
}
Stack& pop() {
if (first == 0) {
cout << "No nodes to pop.\n";
} else {
if (first == last) {
cout << "Popped " << first->data << " off the stack\n";
delete first;
first = 0;
last = 0;
return *this;
}
Node* temp = first;
while (temp->next != last) {
temp = temp->next;
}
cout << "Popped " << last->data << " off the stack\n";
delete last;
last = temp;
last->next = 0;
}
return *this;
}
};
int main() {
Stack s;
s.pop();
s.push(1);
s.push(2);
s.pop();
s.push(3).push(4);
s.pop().pop();
return 0;
}