DSU Unit 3 Q and A
DSU Unit 3 Q and A
DSU Unit 3 Q and A
4. Create a Singly linked list using data fields 70, 50, 30, 40, 90. Search a
node 40 from the singly linked list & show procedure step-by-step
with the help of diagram from start to end.
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
struct Node* createNode(int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = NULL;
return newNode;
}
void insertAtEnd(struct Node** head, int data) {
struct Node* newNode = createNode(data);
if (*head == NULL) {
*head = newNode;
} else {
struct Node* temp = *head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newNode;
}
}
int searchNode(struct Node* head, int target) {
struct Node* current = head;
int position = 1;
while (current != NULL) {
if (current->data == target) {
return position;
}
current = current->next;
position++;
}
return -1; // Element not found
}
void printList(struct Node* head) {
struct Node* temp = head;
while (temp != NULL) {
printf("%d -> ", temp->data);
temp = temp->next;
}
printf("NULL\n");
}
int main() {
struct Node* head = NULL;
insertAtEnd(&head, 70);
insertAtEnd(&head, 50);
insertAtEnd(&head, 30);
insertAtEnd(&head, 40);
insertAtEnd(&head, 90);
printf("Created Linked List: ");
printList(head);
int target = 40;
int position = searchNode(head, target);
if (position != -1) {
printf("Element %d found at position %d in the linked list.\n", target,
position);
} else {
printf("Element %d not found in the linked list.\n", target);
}
return 0;
}
Step-by-Step Explanation and Diagram
1. Creating the Linked List:
- We begin by creating the linked list with the nodes containing values `70`,
`50`, `30`, `40`, and `90` in that order.
- Initial List:
Head -> 70 -> 50 -> 30 -> 40 -> 90 -> NULL
2. Search Procedure:
- We search for the node containing the value `40`.
- Step-by-Step Search:
- Start at the head (`70`).
- Move to the next node (`50`).
- Move to the next node (`30`).
- Move to the next node (`40`), which is the target value.
- Traversal Visualization:
Head -> 70 -> 50 -> 30 -> [40] -> 90 -> NULL
^
|
Target found
3. Output:
- The program will output that the element `40` is found at position `4` in the
linked list.
Program Output
Created Linked List: 70 -> 50 -> 30 -> 40 -> 90 -> NULL
Element 40 found at position 4 in the linked list.