Write the C function deleteBack that deletes the last node i
Solution
Ques 1
#include <stdio.h>
#include <stdlib.h>
//linked list node
struct node
{
int data;
struct node *next;
};
// function to create a linked list
void push(struct node** head_ref, int new_data)
{
struct node* new_node = (struct node*) malloc(sizeof(struct node));
new_node->data = new_data;
new_node->next = (*head_ref);
(*head_ref) = new_node;
}
// function to delete last node of linked list
void deleteBlack(struct node **head_ref)
{
struct node* temp = *head_ref, *prev;
// if head node is NULL return do nothing
if(temp == NULL )
return ;
// if head node is not null delete the lst node
while(temp->next!=NULL){
prev = temp;
temp = temp->next;
}
prev->next = NULL;
free(temp); // Free memory
}
// This function prints contents of linked list starting from
// the given node
void printList(struct node *node)
{
while (node != NULL)
{
printf(\" %d \", node->data);
node = node->next;
}
}
/* Drier program to test above functions*/
int main()
{
/* Start with the empty list */
struct node* head = NULL;
push(&head, 7);
push(&head, 1);
push(&head, 3);
push(&head, 2);
puts(\"Created Linked List: \");
printList(head);
deleteBlack(&head);
puts(\"\ Linked List after Deletion of 1: \");
printList(head);
return 0;
}
Ques 2
// A complete working C program to demonstrate deletion in singly
// linked list
#include <stdio.h>
#include <stdlib.h>
// A linked list node
struct node
{
int data;
struct node *next;
};
/* Given a reference (pointer to pointer) to the head of a list
and an int, inserts a new node on the front of the list. */
void push(struct node** head_ref, int new_data)
{
struct node* new_node = (struct node*) malloc(sizeof(struct node));
new_node->data = new_data;
new_node->next = (*head_ref);
(*head_ref) = new_node;
}
/* Given a reference (pointer to pointer) to the head of a list
and a key, deletes the first occurrence of key in linked list */
void duplicateLastNode(struct node **head_ref)
{
// Store head node
struct node* temp = *head_ref;
if(temp == NULL )
return ;
while(temp->next!=NULL){
temp = temp->next;
}
struct node* prev = (struct node*) malloc(sizeof(struct node));
prev->data = temp->data;
temp->next = prev;
prev->next = NULL;
}
// This function prints contents of linked list starting from
// the given node
void printList(struct node *node)
{
while (node != NULL)
{
printf(\" %d \", node->data);
node = node->next;
}
}
/* Drier program to test above functions*/
int main()
{
/* Start with the empty list */
struct node* head = NULL;
push(&head, 7);
push(&head, 1);
push(&head, 3);
push(&head, 2);
puts(\"Created Linked List: \");
printList(head);
duplicateLastNode(&head);
puts(\"\ Linked List after Deletion of 1: \");
printList(head);
return 0;
}


