Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
MyStack
//Title of this code #include <iostream> using namespace std; struct Node { int data; Node* next; Node(int d, Node *n) : data(d), next(n) {} }; struct SortedNode { Node* node; SortedNode* next; SortedNode(Node *no, SortedNode *ne) : node(no), next(ne) {} }; class Stack { Node *lifoHead; SortedNode *sortedHead; public: Stack() { lifoHead = NULL; sortedHead = NULL; } ~Stack() { SortedNode *scur = sortedHead; while (scur) { SortedNode *st = scur->next; delete scur; scur = st; } Node *lcur = lifoHead; while (lcur) { Node *lt = lcur->next; delete lcur; lcur = lt; } } void push(int d) { Node *lnode = new Node(d, lifoHead); lifoHead = lnode; SortedNode *cur = sortedHead; SortedNode *tmp = NULL; while (cur) { if (cur->node->data > d) tmp = cur; else break; cur = cur->next; } if (tmp) { SortedNode *t = tmp->next; tmp->next = new SortedNode(lnode, t); } else { SortedNode *snode = new SortedNode(lnode, sortedHead); sortedHead = snode; } } int popBiggest() { if (sortedHead) return sortedHead->node->data; return -1; } int pop() { if (lifoHead) return lifoHead->data; return -1; } void removeTop() { if (lifoHead) { // delete from sorted list SortedNode *cur = sortedHead; SortedNode *prev = NULL; while (cur) { if (cur->node != lifoHead) { prev = cur; cur = cur->next; } else { break; } } if (prev) { prev->next = cur->next; } else sortedHead = cur->next; delete cur; // delete from lifo list Node* tmpLifoNode = lifoHead; lifoHead = lifoHead->next; delete tmpLifoNode; } } void printSorted() { SortedNode *cur = sortedHead; while (cur) { cout << cur->node->data << " "; cur = cur->next; } cout << endl; } void printLifo() { Node *cur = lifoHead; while (cur) { cout << cur->data << " "; cur = cur->next; } cout << endl; } }; int main() { Stack stack; stack.push(3); stack.push(2); stack.push(6); stack.push(5); stack.printSorted(); stack.printLifo(); cout << stack.pop() << endl; stack.removeTop(); stack.printSorted(); stack.printLifo(); cout << stack.popBiggest() << endl; }
run
|
edit
|
history
|
help
0
Prime calculator using bool
DailyExchRate2
Day3
CPP - Arrays - Ex.2
ClassQuiz
Test 13(2020)
Zahra_matrix
ONP
Elevator 3
good triplet