Program C
Program C
Detailed Explanation
1. Node Structure
int data;
} Node;
• This defines a Node structure for a doubly linked list, where each node contains:
if (current->data < 0) {
free(current);
current = next;
}
}
• This function deletes all nodes with negative values from the list.
• If a node’s data is negative, it adjusts the pointers of the previous and next nodes to bypass
the current node.
Node* i, *j;
int temp;
temp = i->data;
i->data = j->data;
j->data = temp;
• This function sorts the list in ascending order using a simple bubble sort algorithm.
• It uses two nested loops to compare each pair of nodes and swaps their data if they are out
of order.
newNode->data = value;
newNode->next = *head;
newNode->prev = NULL;
if (*head != NULL) (*head)->prev = newNode;
*head = newNode;
return;
current = current->next;
newNode->next = current->next;
current->next = newNode;
newNode->prev = current;
• This function inserts a new node with the given value into the list while maintaining the
sorted order.
• It creates a new node and finds the correct position for it by traversing the list.
• It adjusts the pointers of the surrounding nodes to insert the new node in the correct
position.
newNode->data = current->data;
newNode->next = newHead;
newNode->prev = NULL;
newHead = newNode;
current = current->next;
return newHead;
}
• This function creates a new list that is the reverse of the original list.
• It iterates through the original list, creating new nodes and inserting them at the beginning of
the new list.
temp = current->prev;
current->prev = current->next;
current->next = temp;
current = current->prev;
• This function reverses the list in place without allocating new memory.
• After the loop, it updates the head pointer to the new head of the reversed list.
Node* next;
next = current->next;
free(current);
current = next;
*head = NULL;
}
• This function frees the memory allocated for all nodes in the list.
• It iterates through the list, freeing each node and setting the head pointer to NULL.
current = current->next;
printf("\n");
9. Main Function
int main() {
insertSorted(&head, 5);
insertSorted(&head, -3);
insertSorted(&head, 10);
insertSorted(&head, 1);
insertSorted(&head, -1);
printList(head);
deleteNegativeNodes(&head);
printList(head);
sortList(&head);
printf("After sorting: ");
printList(head);
insertSorted(&head, 7);
printList(head);
printList(reversedHead);
reverseWithoutAllocations(&head);
printList(head);
releaseList(&head);
releaseList(&reversedHead);
return 0;
• The main function demonstrates the use of all the functions defined above.
• It creates a list, performs various operations on it, and prints the list after each operation.