The following is the entire function for implementing a doubly linked list. Can anyone show me if there is a better way to write these functions, especially the delete_at function please?
#include<stdio.h>
#include<stdlib.h>
typedef struct linked_list
{
int point;
struct linked_list *p_node;
struct linked_list *n_node;
}node;
node *create_head_node(node *, int);
node *insert_head(node *, int);
void insert_tail(node *, int);
node *insert_at(node *, int, int);
int count_node(node *);
void print_list(node *);
node *delete_tail(node *);
node *delete_head(node *);
node *delete_at(node *, int);
node *create_head_node(node *head, int point){
head->point=point;
head->p_node=NULL;
head->n_node=NULL;
return head;
}
node *insert_head(node *head, int point){
if (head==NULL){
printf("no head exist");
return 0;
}
node *temp=(node*)malloc(sizeof(node));
temp->point=point;
temp->p_node=NULL;
temp->n_node=head;
head->p_node=temp;
head=temp;
return head;
}
void insert_tail(node *head, int point){
if (head==NULL){
printf("no head exist");
return;
}
node *p=head;
node *temp=(node*)malloc(sizeof(node));
temp->point=point;
temp->n_node=NULL;
while (p->n_node!=NULL)
{
p=p->n_node;
}
p->n_node=temp;
temp->p_node=p;
}
node *insert_at(node *head, int point, int pos){
if (head==NULL){
printf("no head exist");
return 0;
}
int count=count_node(head);
while (pos>count)
{
printf("choose %d positions to add. choose again: ", count); scanf("%d", &pos);
}
node *p=head;
for (int i = 0; i < pos; i++)
{
p=p->n_node;
}
node *temp=(node*)malloc(sizeof(node));
temp->point=point;
temp->n_node=p;
temp->p_node=p->p_node;
if(p->p_node!=NULL) p->p_node->n_node=temp;
p->p_node=temp;
return head;
}
int count_node(node *head){
node *p=head;
int count=0;
while (p!=NULL)
{
count++;
p=p->n_node;
}
free(p);
return count;
}
void print_list(node *head){
if (head==NULL){ printf("nothing to print"); return;}
node *p=head;
while (p!=NULL)
{
printf("%d ", p->point);
p=p->n_node;
}
}
node *delete_head(node *head){
if (head==NULL){
printf("no head exist\n");
return 0;
}
node *p=head;
// head->p_node=NULL;
if(p->n_node!=NULL){
head=p->n_node;
free(p);
}
else head=NULL;
return head;
}
node *delete_tail(node *head){
if (head==NULL){
printf("no head exist\n");
return 0;
}
node *p=head;
while (p->n_node!=NULL)
{
p=p->n_node;
}
if (p->p_node!=NULL){
p->p_node->n_node=NULL;
free(p);
}
else head=NULL;
return head;
}
node *delete_at(node *head, int pos){
int count=count_node(head);
if(head==NULL){
printf("no head exist");
return 0;
}
while (count<pos)
{
printf("choose %d positions to delete. choose again", count); scanf("%d", &pos);
}
node *p=head;
if(pos==0) head=delete_head(head);
else if(pos==count-1) head=delete_tail(head);
else{
for (int i = 0; i < pos; i++)
{
p=p->n_node;
}
p->p_node->n_node=p->n_node;
p->n_node->p_node=p->p_node;
free(p);
}
return head;
}
head->n_node =insert_tail runs through the list (if head->n_node is set anywhere) instead of using the head->p_node. \$\endgroup\$