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;
- node * prev;
- };
- struct DLL {
- node * head;
- void init() {
- head = NULL;
- }
- void insertFront(int x) {
- node * new_node = new node;
- new_node->info = x;
- new_node->next = NULL;
- new_node->prev = NULL;
- if(head == NULL) {
- head = new_node;
- }
- else {
- new_node->next = head;
- head->prev = new_node;
- head = new_node;
- }
- }
- void insertEnd(int x) {
- node * new_node = new node;
- new_node->info = x;
- new_node->next = NULL;
- new_node->prev = NULL;
- if(head == NULL) {
- head = new_node;
- }
- else {
- node * tmp = head;
- while(tmp->next != NULL) {
- tmp = tmp->next;
- }
- tmp->next = new_node;
- new_node->prev = tmp;
- }
- }
- void deleteFront() {
- if(head != NULL) {
- if(head->next == NULL) {
- delete head;
- head = NULL;
- }
- else {
- head = head->next;
- delete head->prev;
- head->prev = NULL;
- }
- }
- }
- void deleteEnd() {
- if(head != NULL) {
- if(head->next == NULL) {
- delete head;
- head = NULL;
- }
- else {
- node * tmp = head;
- while(tmp->next != NULL) {
- tmp = tmp->next;
- }
- tmp->prev->next = NULL;
- delete tmp;
- tmp = NULL;
- }
- }
- }
- void deleteAll() {
- while(head != NULL) {
- deleteEnd();
- }
- }
- void deleteNode(int x) {
- if(head != NULL) {
- if(head->info == x) {
- deleteFront();
- }
- else {
- node * tmp = head;
- while(tmp != NULL and tmp->info != x) {
- tmp = tmp->next;
- }
- if(tmp->next == NULL) {
- deleteEnd();
- }
- else {
- tmp->prev->next = tmp->next;
- tmp->next->prev = tmp->prev;
- delete tmp;
- }
- }
- }
- }
- void deleteNode(node * x) {
- if(head != NULL) {
- if(head == x) {
- deleteFront();
- }
- else {
- node * tmp = head;
- while(tmp != NULL and tmp != x) {
- tmp = tmp->next;
- }
- if(tmp->next == NULL) {
- deleteEnd();
- }
- else {
- tmp->prev->next = tmp->next;
- tmp->next->prev = tmp->prev;
- delete tmp;
- }
- }
- }
- }
- void print() {
- node * tmp = head, * last;
- while(tmp != NULL) {
- last = tmp;
- cout << tmp->info << "->";
- tmp = tmp -> next;
- }
- cout << endl;
- while(last != NULL) {
- cout << last->info << "<--";
- last = last->prev;
- }
- cout << endl;
- }
- };
- int main() {
- DLL dll;
- dll.init();
- dll.insertFront(1);
- dll.insertFront(2);
- dll.insertFront(3);
- dll.insertEnd(4);
- dll.insertEnd(5);
- dll.insertEnd(6);
- dll.print();
- dll.deleteNode(4);
- dll.print();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement