Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include "pch.h"
- #include <iostream>
- struct Node
- {
- int data;
- Node* next;
- };
- class MyList {
- Node* head;
- Node* tail = new Node;
- public:
- bool is_empty()
- {
- return head == NULL;
- }
- int pop()
- {
- int data;
- Node* p;
- if (tail)
- {
- data = tail->data;
- p = previous(tail);
- p->next = NULL;
- delete tail;
- tail = p;
- }
- return data;
- }
- void pop(int &data)
- {
- Node* p;
- if (!is_empty())
- {
- data = tail->data;
- p = tail->next;
- delete tail;
- tail = p;
- }
- }
- void push(int data)
- {
- Node* p = new Node;
- p->data = data;
- p->next = NULL;
- if (is_empty()) {
- head = tail = p;
- }
- else {
- tail->next = p;
- tail = p;
- }
- }
- void show_list()
- {
- Node* p;
- p = head;
- while (p)
- {
- std::cout << p->data << " ";
- p = p->next;
- }
- std::cout << std::endl;
- }
- Node* previous(Node* p) {
- Node* pr, *q;
- q = head;
- pr = NULL;
- while (q != p && q) {
- pr = q;
- q = q->next;
- }
- if (q == p) return pr;
- return NULL;
- }
- void insert_before(Node* q, int x)
- {
- Node* p, *r;
- p = new Node;
- r = previous(q);
- if (q == tail)
- push(x);
- else
- if (r == NULL)
- {
- std::cout << " sorry, impossible insert element " << std::endl;
- exit(-1);
- }
- else
- {
- p->data = x;
- p->next = r->next;
- r->next = p;
- }
- }
- void insert_after(Node* &q, int x)
- {
- Node* p;
- p = new Node;
- p->data = x;
- p->next = q->next;
- q->next = p;
- }
- Node* find_address(int x)
- {
- Node* p = head;
- while (p && (p->data) != x)
- p = p->next;
- return p;
- }
- void delete_element(Node* p)
- {
- Node* r; int x;
- if (p == tail)
- pop(x);
- else
- {
- r = previous(p);
- r->next = p->next;
- delete p;
- }
- }
- };
- int main()
- {
- MyList list;
- for (int i = 0; i < 150; i++) {
- list.push(i);
- }
- list.show_list();
- list.pop();
- list.show_list();
- auto a = list.find_address(20);
- list.insert_after(a, 505);
- list.show_list();
- list.insert_before(a, 404);
- list.show_list();
- list.delete_element(a);
- list.show_list();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement