Linked List Insert
C
Medium
4 views
Problem Description
Create Node structure (data, next pointer). Create Functions: insertAtBeginning(), insertAtEnd(), insertAtPosition(), display(). Proper pointer manipulation.
Official Solution
#include <stdio.h>
#include <stdlib.h>
// Node structure
struct Node {
int data;
struct Node *next;
};
// Insert at beginning
void insertAtBeginning(struct Node **head, int value) {
struct Node *newNode = (struct Node *)malloc(sizeof(struct Node));
newNode->data = value;
newNode->next = *head;
*head = newNode;
}
// Insert at end
void insertAtEnd(struct Node **head, int value) {
struct Node *newNode = (struct Node *)malloc(sizeof(struct Node));
struct Node *temp = *head;
newNode->data = value;
newNode->next = NULL;
if (*head == NULL) {
*head = newNode;
return;
}
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newNode;
}
// Insert at specific position (1-based index)
void insertAtPosition(struct Node **head, int value, int position) {
int i;
struct Node *temp = *head;
if (position == 1) {
insertAtBeginning(head, value);
return;
}
for (i = 1; i < position - 1 && temp != NULL; i++) {
temp = temp->next;
}
if (temp == NULL) {
printf("Invalid position!n");
return;
}
struct Node *newNode = (struct Node *)malloc(sizeof(struct Node));
newNode->data = value;
newNode->next = temp->next;
temp->next = newNode;
}
// Display list
void display(struct Node *head) {
if (head == NULL) {
printf("List is empty.n");
return;
}
printf("Linked List: ");
while (head != NULL) {
printf("%d -> ", head->data);
head = head->next;
}
printf("NULLn");
}
// Main function
int main() {
struct Node *head = NULL;
insertAtBeginning(&head, 10);
insertAtEnd(&head, 20);
insertAtEnd(&head, 30);
insertAtPosition(&head, 25, 3);
display(head);
return 0;
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!