Monday, 9 December 2024

Functions

 Solve :- insert a node at the start of a DLL

// Function to insert a node at the beginning of the doubly linked list

 struct Node* insertAtBeginning(struct Node* head, int value)

 { 

// Step 1: Create a new node with the given value

 struct Node* newNode = createNode(value);

 // Step 2: If the list is not empty, update the current head's previous pointer 

if (head != NULL) 

head->prev = newNode;

 } 

// Step 3: Make the new node's next pointer point to the current head

 newNode->next = head; 

// Step 4: Update the head to point to the new node

 head = newNode;

 // Return the new head of the list 

return head; 

    Write a function to sort a DLL

sort(struct node **head)

// pointer to the pointer of the head node of the linked list.
{
struct node *n, *c;

// declares two pointers to nodes in a linked list.
int x;

for (c = *head; c-> next ! = NULL, c = c->next)

//   c = *head: Start at the first node of the list.

 // c->next != NULL: Check if the current node has a next node; continue if true.

//  c = c->next: Move to the next node in the list.

for(n = c->next; n!=NULL; n=n->next)

{

//compare (swap logic)

   If(c->data > n->data)

{

X = c->data;

c->data = n->data;

n->data = x;

}

}
}


Reverse print a DLL without using recursion

d_rdisplay( struct dnode *q ) 

Struct dnode *temp=*q;


while ( temp->next != NULL )

 

//checks if the current node (temp) has a next node (i.e., temp->next is not NULL).


temp = temp->next;


//temp = temp->next;: This moves the pointer temp to the next node in the list.


while(temp!=NULL)

{

printf ( "%d ", temp -> data ) ; 

temp = temp -> next ; 

 The code loops through the linked list, printing the data of each node, and moves to the next node until it reaches the end (when temp is NULL).