Queue:
Doubly linked list:
#include <iostream>
using namespace std;
struct ListNode {
int val;
ListNode *next, *pre;
ListNode(int x) :val(x), next(NULL), pre(NULL) {}
};
class Queue {
private: ListNode *first, *last;
public:
Queue() {first=NULL; last=NULL;}
void add(int value);
int remove();
};
void Queue::add(int value) {
if (!first) {
last = new ListNode(value);
first = last;
}else {
ListNode *newNode = new ListNode(value);
last->next = newNode;
newNode->pre = last;
last = last->next;
}
}
int Queue::remove() {
int res=0;
if (first) {
res = first->val;
first = first->next;
return res;
}
return 0;
}
// Should print:
// 1
// 2
// 3
int main() {
cout << "Starting\n";
Queue q;
q.add(1);
q.add(2);
cout << q.remove() << "\n";
q.add(3);
cout << q.remove() << "\n";
cout << q.remove() << "\n";
return 0;
}
Singly linked list : 1->2->3
#include <iostream>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) :val(x), next(NULL) {}
};
class Queue {
private: ListNode *first, *last;
public:
Queue() {first=NULL; last=NULL;}
void add(int value);
int remove();
};
void Queue::add(int value) {
if (!first) {
last = new ListNode(value);
first = last;
}else {
ListNode *newNode = new ListNode(value);
last->next = newNode;
last = last->next;
}
}
int Queue::remove() {
int res=0;
if (first) {
res = first->val;
first = first->next;
return res;
}
return 0;
}
Stack:
Singly linked list 3->2->1
#include <iostream>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) :val(x), next(NULL) {}
};
class Stack {
private:
//vector<int> items;
//int num;
ListNode *top;
public:
Stack() {top = NULL;}
void add(int value);
int remove();
};
void Stack::add(int value) {
if (!top) {
top = new ListNode(value);
}else {
ListNode *newNode = new ListNode(value);
newNode->next = top;
top = newNode;
}
}
int Stack::remove() {
int res=0;
if (top) {
res = top->val;
top = top->next;
return res;
}
return 0;
}
// Should print:
// 2
// 3
// 1
int main() {
cout << "Starting\n";
Stack s;
s.add(1);
s.add(2);
cout << s.remove() << "\n";
s.add(3);
cout << s.remove() << "\n";
cout << s.remove() << "\n";
return 0;
}