Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- using namespace std;
- struct Node
- {
- int info;
- Node* next;
- };
- class Lista
- {
- public:
- Node* head;
- int counter = 0;
- Lista()
- {
- head = NULL;
- }
- void printList();
- void insert(int val, int pos);
- void deleteByPos(int pos);
- void reverse();
- void deleteList();
- };
- void Lista::printList()
- {
- for (Node* p = head; p != NULL; p = p->next)
- {
- cout << p->info;
- if (p->next == NULL)
- cout<<". ";
- else
- cout<<", ";
- }
- cout<<"\n";
- }
- void Lista::insert(int val, int pos)
- {
- Node *p = new Node;
- p->info = val;
- p->next = NULL;
- counter++;
- if (head == NULL) // inserare lista goala
- {
- head = p;
- return;
- }
- if (pos == 0) //inserare la inceput
- {
- p -> next = head;
- head = p;
- return;
- }
- int i = 0; //inserare dupa o anumita pozitie
- Node* temp;
- temp = head;
- while(temp->next != NULL && i != pos - 1) //parcurgem lista pana pe pozitia pos - 1
- {
- temp = temp -> next;
- i++;
- }
- p->next = temp->next;
- temp->next = p;
- }
- void Lista::deleteByPos(int pos)
- {
- counter--;
- if (head == NULL) //daca lista e goala
- return;
- if (pos == 0) //daca stergem primul element
- {
- Node* p = head;
- delete p;
- head = head -> next;
- return;
- }
- int i = 0; //stergere la o anumita pozitie
- Node* temp;
- temp = head;
- while(temp->next != NULL && i != pos - 1) //parcurgem lista pana pe pozitia pos - 1
- {
- temp = temp -> next;
- i++;
- }
- Node* p;
- p = temp->next;
- delete p;
- if(temp->next->next != NULL)
- temp->next = temp->next->next;
- else
- temp->next = NULL;
- }
- void Lista::reverse()
- {
- Node *current = head, *prev = NULL, *urm = NULL;
- while (current != NULL)
- {
- urm = current->next;
- current->next = prev;
- prev = current;
- current = urm;
- }
- head = prev;
- }
- void Lista::deleteList()
- {
- Node *p;
- p = head;
- while (head != NULL)
- {
- head = head->next;
- delete p;
- p = head;
- counter--;
- }
- }
- int main()
- {
- Lista l;
- l.insert(10,0);
- l.insert(20,0);
- l.insert(15,1);
- l.printList();
- l.deleteList();
- l.printList();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement