From 98d54a67d17e8d1f1c7d28f5e04b736a4f196f44 Mon Sep 17 00:00:00 2001 From: Vinayak Ravi Joshi <41225554+v007rj@users.noreply.github.com> Date: Tue, 9 Feb 2021 18:54:16 +0530 Subject: [PATCH] Code for inserting elements in doubly linked list (#67) * Code for inserting elements in doubly linked list * Circular linked list added --- linked-lists/README.md | 4 +++ linked-lists/c-or-cpp/circular.cpp | 39 ++++++++++++++++++++++++++++++ linked-lists/c-or-cpp/doubly.cpp | 36 +++++++++++++++++++++++++++ 3 files changed, 79 insertions(+) create mode 100644 linked-lists/c-or-cpp/circular.cpp create mode 100644 linked-lists/c-or-cpp/doubly.cpp diff --git a/linked-lists/README.md b/linked-lists/README.md index 311ed256..085439a9 100644 --- a/linked-lists/README.md +++ b/linked-lists/README.md @@ -5,6 +5,10 @@ 1. [Singly Linked List](c-or-cpp/singly.cpp) 2. [Reversing Linked List](c-or-cpp/reverse-linkedlist.cpp) +2. [Doubly Linked List](c-or-cpp/doubly.cpp) + +3. [Circular Linked List](c-or-cpp/circular.cpp) + ### Java 1. [Singly Linked List](java/singly.cpp) diff --git a/linked-lists/c-or-cpp/circular.cpp b/linked-lists/c-or-cpp/circular.cpp new file mode 100644 index 00000000..0cf9aaf4 --- /dev/null +++ b/linked-lists/c-or-cpp/circular.cpp @@ -0,0 +1,39 @@ +#include +using namespace std; +struct Node { +   int data; +   struct Node *next; +}; +struct Node* head = NULL; +void insert(int newdata) { +   struct Node *newnode = (struct Node *)malloc(sizeof(struct Node)); +   struct Node *ptr = head; +   newnode->data = newdata; +   newnode->next = head; +   if (head!= NULL) { +      while (ptr->next != head) +      ptr = ptr->next; +      ptr->next = newnode; +   } else +   newnode->next = newnode; +   head = newnode; +} +void display() { +   struct Node* ptr; +   ptr = head; +   do { +      cout<data <<" "; +      ptr = ptr->next; +   } while(ptr != head); +} +int main() { +   insert(3); +   insert(1); +   insert(7); +  insert(3); +   insert(1); +   insert(7); +   cout<<"The circular linked list is: "; +   display(); +   return 0; +} diff --git a/linked-lists/c-or-cpp/doubly.cpp b/linked-lists/c-or-cpp/doubly.cpp new file mode 100644 index 00000000..1cf67434 --- /dev/null +++ b/linked-lists/c-or-cpp/doubly.cpp @@ -0,0 +1,36 @@ +#include +#include +using namespace std; +struct Node { +   int data; +   struct Node *prev; +   struct Node *next; +}; +struct Node* head = NULL; +void insert(int newdata) { +   struct Node* newnode = (struct Node*) malloc(sizeof(struct Node)); +   newnode->data = newdata; +   newnode->prev = NULL; +   newnode->next = head; +   if(head != NULL) +   head->prev = newnode ; +   head = newnode; +} +void display() { +   struct Node* ptr; +   ptr = head; +   while(ptr != NULL) { +      cout<< ptr->data <<" "; +      ptr = ptr->next; +   } +} +int main() { +   insert(3); +   insert(1); +   insert(7); +   insert(2); +   insert(9); +   cout<<"The doubly linked list is: "; +   display(); +   return 0; +}