I am trying to insert a node before another node in a doubly linked list and I have been trying to do for awhile, but I still can't get it =/. I keep getting error whenever I try to display the list after I insert in a new node. Please help.
#include <stdio.h>
#include <stdlib.h>
#define SENT -1
#define MAX 100
typedef struct nodes {
int element;
struct nodes *fp;
struct nodes *bp;
} node_t;
node_t *head, *tail, *current;
void insert_end(node_t *list){
if (head == NULL){
head = list;
list->bp = NULL;}
else {
tail->fp = list;
list->bp = tail;
}
tail = list;
list->fp =NULL;
}
void insert_start(node_t *list, int num){
node_t *newp, *temp = head;
list = head;
newp = (node_t *)malloc(sizeof(node_t));
newp->element = num;
newp->fp = temp;
newp->bp = NULL;
list->bp = newp;
head = newp;
}
//insert a node in front of a selected node
void insert_front(node_t *list, int insert, int node){
int i;
node_t *newp, *temp;
list = head;
i = list->element;
while (list->fp != NULL){
if (i == node) break;
list = list->fp;
i = list->element;
}
newp = (node_t *)malloc(sizeof (node_t));
newp->element = insert;
temp = list;
newp->fp = temp->fp;
temp->fp->fp = newp;
temp->fp = newp;
newp->bp = temp;
list = temp;
}
void prompt(){
printf("\n\n0 Quit\n");
printf("1 Insert node at the beginning of the list\n2 Insert node at the end of the list\n3 Insert node in front of a node\n");
printf("4 Delete node\n");
printf("5 Display-to-rear\n6 Display-to-front\n");
printf("\nYour choice(0-5): ");
}
void display(node_t *list){
printf("Current list: ");
for(list = head; list != NULL; list = list->fp) {
printf("%d ", list->element);}
}
int ask_num(){
int num;
printf("Enter a positive integer: ");
scanf("%d", &num);
return num;
}
int find_num(node_t *list, int num){
int i;
list = head;
i = list->element;
while (list->fp != NULL){
if (i == num) return 1;
list = list->fp;
i = list->element;
}
return 0;
}
int main(int argc, char **argv){
int num, key, node, i, find, num_in_file[MAX];
node_t *my_list;
FILE *inp;
inp = fopen(argv[1], "r");
for (fscanf(inp, "%d", &num), i = 0; num != SENT; ++i, fscanf(inp, "%d", &num)){
num_in_file[i] = num;
}
for (--i, num = num_in_file[i]; i >= 0; --i, num = num_in_file[i]){
my_list = (node_t *)malloc(sizeof(node_t));
my_list->element = num;
insert_end(my_list);
}
fclose(inp);
display(my_list);
do {
prompt();
scanf("%d", &key);
switch (key){
case 0:
break;
case 1:
num = ask_num();
insert_start(my_list, num);
printf("\n");
display(my_list);
break;
case 2:
num = ask_num();
my_list = (node_t *)malloc(sizeof(node_t));
my_list->element = num;
insert_end(my_list);
printf("\n");
display(my_list);
break;
case 3:
num = ask_num();
printf("Insert %d in front of which node? ", num);
scanf("%d", &node);
find = find_num(my_list, node);
if (find == 1){
insert_front(my_list, num, node);}
printf("\n");
display(my_list);
}
}
while (key != 0);
return 0;
}