Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <stack>
- using namespace std;
- struct Node
- {
- int data;
- Node* next;
- };
- void RemoveSingles(Node*& head);
- void Push(Node*& head, int data);
- void Append(Node*& head, int data);
- void printList(Node* head);
- void DeleteList(Node*& head);
- int main()
- {
- Node* llist = nullptr;
- int n;
- cout << "Enter number of elements: ";
- cin >> n;
- cout << "Enter list elements: ";
- for (int i = 0; i < n; i++)
- {
- int num;
- cin >> num;
- Append(llist, num);
- }
- RemoveSingles(llist);
- cout << endl;
- printList(llist);
- return 0;
- }
- void RemoveSingles(Node*& head)
- {
- if (head == nullptr)
- {
- return;
- }
- stack<int> elements;
- Node* current = head;
- while (current != nullptr)
- {
- int num = current->data;
- elements.push(num);
- current = current->next;
- cout << "Push: " << num << endl;
- bool flag = false;
- while (current != nullptr && current->data == num)
- {
- flag = true;
- elements.push(current->data);
- cout << "Push: " << current->data << endl;
- current=current->next;
- }
- if (!flag)
- {
- cout << "Pop: " << elements.top() << endl;
- elements.pop(); // remove single element
- }
- }
- DeleteList(head);
- while (!elements.empty())
- {
- Push(head, elements.top());
- elements.pop();
- }
- }
- void Push(Node*& head, int data)
- {
- Node* n = new Node();
- n->data = data;
- n->next = head;
- head = n;
- }
- void Append(Node*& head, int data)
- {
- Node* n = new Node();
- n->data = data;
- if (head == nullptr)
- {
- n->next = head;
- head = n;
- }
- else
- {
- Node* current = head;
- while(current->next != nullptr)
- {
- current = current->next;
- }
- n->next = current->next;
- current->next = n;
- }
- }
- void printList(Node* head)
- {
- if (head == nullptr)
- {
- cout << "Empty list" << endl;
- }
- Node* current = head;
- while (current != nullptr)
- {
- cout << current->data << " ";
- current = current->next;
- }
- cout << endl;
- }
- void DeleteList(Node*& head)
- {
- Node* current = head;
- Node* todelete;
- while (current != nullptr)
- {
- todelete = current;
- current = current->next;
- delete todelete;
- }
- head = nullptr;
- }
Add Comment
Please, Sign In to add comment