1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
|
#include<stdio.h>
#include<stdlib.h>
void create(struct node **, int );
void display(struct node *);
void insertInDlinkedList(struct node **, int, int);
struct node {
int data;
struct node * prev;
struct node * next;
};
int main()
{
struct node *head;
head = NULL; /*empty doubly linked list*/
create(&head, 11); /* creating the first node with data 11 */
insertInDlinkedList(&head, 20, 1); /*working till this point */
insertInDlinkedList(&head, 23, 1);
insertInDlinkedList(&head, 26, 2);
display(head);
}
void create(struct node **h, int num){
if (*h == NULL){
/*create a new node*/
*h = (struct node *)malloc(sizeof(struct node *));
(*h)->data = num;
(*h)->prev = NULL;
(*h)->next = NULL;
}
}
void insertInDlinkedList(struct node **h, int data, int pos){
struct node *newnode , *temp = nullptr;
int k = 1;
newnode = (struct node *)malloc(sizeof(struct node));
if (!newnode){
printf("Memory Error \n");
return;
}
newnode->data = data;
if (pos == 1){
newnode->next = *h;
newnode->prev= NULL;
(*h)->prev = newnode;
*h = newnode;
//return;
}
else {
temp = *h;
while (temp->next != NULL && (k < pos)){
k++;
temp = temp->next;
}
if (temp->next == NULL){
newnode->next = temp->next;
newnode->prev = temp;
temp->next = newnode;
}
else {
newnode->next = temp->next;
newnode->prev = temp;
temp->next->prev = newnode;
temp->next = newnode;
}
return;
}
}
void display(struct node *h){
struct node * current;
current = h;
printf("inside display\n");
while (current != NULL){
printf("%d ->", current->data);
current = current->next;
}
printf("NULL");
printf("\n");
}
|