Can somebody please specify why this deleteB
function is leaving a trailing 0 at the end after deleting. I tried this method out of curiosity.
I tried to access the previous pointer of head and making it's next pointer point to head->next
instead of head
.
After that I am changing the previous pointer of head->next
and make it point to head->prev
instead of head
.
Finally I free
the temp
after changing the head
.
Maybe method is wrong...Guide me if am wrong.
#include <stdio.h>
#include <stdlib.h>
typedef struct Node
{
int data;
struct Node *prev;
struct Node *next;
} Node;
void deleteB(Node **head)
{
if (*head != NULL)
{
if ((*head)->next == *head)
{
*head = NULL;
return;
}
Node *temp = *head;
(*head)->prev->next = (*head)->next;
(*head)->next->prev = (*head)->prev;
*head = (*head)->next;
free(temp);
// Node *curr = *head;
// while (curr->next != *head)
// {
// curr = curr->next;
// }
// curr->next = (*head)->next;
// (*head)->next->prev = curr;
// *head = (*head)->next;
// free(temp);
}
}
void prepend(Node **head, int value)
{
Node *newNode = (Node *)malloc(sizeof(Node));
newNode->prev = NULL;
newNode->next = NULL;
newNode->data = value;
if (*head == NULL)
{
*head = newNode;
(*head)->next = *head;
(*head)->prev = *head;
return;
}
Node *temp = *head;
while (temp->next != *head)
{
temp = temp->next;
}
temp->next = newNode;
newNode->prev = temp;
newNode->next = *head;
*head = newNode;
}
void append(Node **head, int value)
{
Node *newNode = (Node *)malloc(sizeof(Node));
newNode->prev = NULL;
newNode->next = NULL;
newNode->data = value;
if (*head == NULL)
{
*head = newNode;
(*head)->next = *head;
(*head)->prev = *head;
return;
}
Node *temp = *head;
while (temp->next != *head)
{
temp = temp->next;
}
temp->next = newNode;
newNode->prev = temp;
newNode->next = *head;
}
void display(Node *head)
{
printf("\nPrinting the list: ");
Node *temp = head;
do
{
printf("-->%d", temp->data);
temp = temp->next;
} while (temp != head);
}
int main()
{
Node *head = NULL;
append(&head, 1);
append(&head, 2);
append(&head, 3);
append(&head, 4);
// insertAtN(&head, 9, 1);
deleteB(&head);
display(head);
printf("\n");
return 0;
}