Week 10 Linked List
Week 10 Linked List
#include <stdio.h>
#include <stdlib.h>
if (*head == NULL) {
*head = newNode;
} else {
While (temp->next != NULL) {
Temp = temp->next;
}
Temp->next = newNode;
}
}
// Function to print a linked list
Void printList(struct Node* head) {
Struct Node* temp = head;
While (temp != NULL) {
Printf(“%d “, temp->data);
Temp = temp->next;
}
Printf(“\n”);
}
// Function to split linked list into two lists: odd and even nodes
Void splitList(struct Node* head, struct Node** oddList, struct Node** evenList) {
Struct Node* odd = NULL;
Struct Node* even = NULL;
Struct Node* current = head;
Int index = 1;
Int main() {
Struct Node* originalList = NULL;
Struct Node* oddList = NULL;
Struct Node* evenList = NULL;
If (choice == 1) {
Printf(“Enter value: “);
Scanf(“%d”, &value);
insertNode(&originalList, value);
} else if (choice == 2) {
Break;
} else {
Printf(“Invalid choice!\n”);
}
}
return 0;
}
Q2
#include <stdio.h>
#include <stdlib.h>
if (*head == NULL) {
*head = newNode;
} else {
While (temp->next != NULL) {
Temp = temp->next;
}
Temp->next = newNode;
}
}
// Function to find the value at n’th node from the end of the linked list
Int findNthFromEnd(struct Node* head, int n) {
Struct Node* first = head;
Struct Node* second = head;
Int count = 0;
// Move both pointers until the first pointer reaches the end
While (first != NULL) {
First = first->next;
Second = second->next;
}
// The second pointer is now at the n’th node from the end
Return second->data;
}
Int main() {
Struct Node* head = NULL;
Int choice, value, n;
If (choice == 1) {
Printf(“Enter value: “);
Scanf(“%d”, &value);
insertNode(&head, value);
} else if (choice == 2) {
Break;
} else {
Printf(“Invalid choice!\n”);
}
}
// Output the original list
Printf(“Linked List: “);
printList(head);
If (result != -1) {
Printf(“Value at position %d from end: %d\n”, n, result);
}
Return 0;
}
Q3
#include <stdio.h>
#include <stdlib.h>
if (*head == NULL) {
*head = newNode;
} else {
While (temp->next != NULL) {
Temp = temp->next;
}
Temp->next = newNode;
}
}
// Update the head pointer to the new head (last node of original list)
*head = prev;
}
Int main() {
Struct Node* head = NULL;
Int choice, value;
If (choice == 1) {
Printf(“Enter value: “);
Scanf(“%d”, &value);
insertNode(&head, value);
} else if (choice == 2) {
Break;
} else {
Printf(“Invalid choice!\n”);
}
}
return 0;
}