Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- using namespace std;
- struct node {
- int val;
- node * next;
- node * prev;
- };
- struct DLL {
- node *head;
- void init() {
- head = NULL;
- }
- void insertBegin(int x) {
- node * new_node = new node;
- new_node->val = 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->val = 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 deleteBegin() {
- if(head != NULL) {
- if(head->next == NULL) {
- delete head;
- head = NULL;
- }
- else {
- node *tmp = head;
- head = head->next;
- head->prev = NULL;
- delete tmp;
- }
- }
- }
- 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;
- tmp->prev = NULL;
- delete tmp;
- }
- }
- }
- void deleteAll() {
- while(head != NULL) {
- deleteBegin();
- }
- }
- void print() {
- node * tmp = head, *last_node;
- while(tmp != NULL) {
- cout << tmp->val << " <--> ";
- last_node = tmp;
- tmp = tmp->next;
- }
- cout << endl;
- while(last_node != NULL) {
- cout << last_node->val << " <--> ";
- last_node = last_node->prev;
- }
- cout << endl;
- }
- };
- int main() {
- DLL dll;
- dll.init();
- dll.insertBegin(1);
- dll.insertBegin(2);
- dll.insertEnd(3);
- dll.insertEnd(4);
- dll.insertEnd(5);
- dll.print();
- dll.deleteBegin();
- dll.print();
- dll.deleteEnd();
- dll.print();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement