So I wrote some code for a doubly-linked list and while making a function for adding a node at the end, I thought of making a pointer for the last node, but when I execute it for adding at last it crashes but adding at front end it works fine. Everything looks fine and it does not even show any error but just crashes.
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *lptr;
struct node *rptr;
};
typedef struct node *Node;
Node pos(Node first, Node last)
{
Node new;
new = (Node)malloc(sizeof(struct node));
new->lptr = NULL;
new->rptr = NULL;
printf("Enter data: ");
scanf("%d", &new->data);
if (first == NULL)
{
first = new;
last = new;
}
else
{
int p;
printf("1) First\n2) Last\n");
scanf("%d", &p);
switch (p)
{
case 1:
first->lptr = new;
new->rptr = first;
first = new;
break;
case 2:
last->rptr = new;
new->lptr = last;
last = new;
break;
default:
break;
}
}
return first;
}
void dis(Node first)
{
Node p;
int c = 1;
if (first == NULL)
{
printf("Empty");
}
else
{ p=first;
while (p != NULL)
{
printf("%dst element is %d\n", c, p->data);
c++;
p = p->rptr;
}
}
}
int main()
{
int ch;
Node first, last, t;
first = NULL;
last = NULL;
for (;;)
{
printf("Insert: \n");
scanf("%d", &ch);
switch (ch)
{
case 1:
first = pos(first, last);
break;
case 2:
dis(first);
break;
default:
printf("invalid");
exit(0);
}
}
return 0;
}
Think the problem is in this part;
case 2:
last->rptr = new;
new->lptr = last;
last = new;
break;