Untitled
unknown
plain_text
3 years ago
2.9 kB
9
Indexable
#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 insertAtBeginning(struct Node** head, int data) {
struct Node* newNode = createNode(data);
newNode->next = *head;
*head = newNode;
printf("%d inserted at beginning.\n", data);
}
void insertAtEnd(struct Node** head, int data) {
struct Node* newNode = createNode(data);
if (*head == NULL) {
*head = newNode;
}
else {
struct Node* lastNode = *head;
while (lastNode->next != NULL) {
lastNode = lastNode->next;
}
lastNode->next = newNode;
}
printf("%d inserted at end.\n", data);
}
void insertAtPosition(struct Node** head, int data, int position) {
struct Node* newNode = createNode(data);
if (position == 1) {
newNode->next = *head;
*head = newNode;
printf("%d inserted at position %d.\n", data, position);
return;
}
struct Node* prevNode = *head;
for (int i = 1; i < position - 1 && prevNode != NULL; i++) {
prevNode = prevNode->next;
}
if (prevNode == NULL) {
printf("Invalid position %d\n", position);
return;
}
newNode->next = prevNode->next;
prevNode->next = newNode;
printf("%d inserted at position %d.\n", data, position);
}
void deleteAtPosition(struct Node** head, int position) {
if (*head == NULL) {
printf("List is empty.\n");
return;
}
struct Node* tempNode = *head;
if (position == 1) {
*head = tempNode->next;
free(tempNode);
printf("Node deleted at position %d.\n", position);
return;
}
struct Node* prevNode = NULL;
for (int i = 1; i < position && tempNode != NULL; i++) {
prevNode = tempNode;
tempNode = tempNode->next;
}
if (tempNode == NULL) {
printf("Invalid position %d\n", position);
return;
}
prevNode->next = tempNode->next;
free(tempNode);
printf("Node deleted at position %d.\n", position);
}
void search(struct Node* head, int key) {
struct Node* tempNode = head;
int position = 1;
while (tempNode != NULL && tempNode->data != key) {
tempNode = tempNode->next;
position++;
}
if (tempNode == NULL) {
printf("%d not found in the list.\n", key);
}
else {
printf("%d found at position %d.\n", key, position);
}
}
void display(struct Node* head) {
struct Node* tempNode = head;
if (tempNode == NULL) {
printf("List is empty.\n");
}
else {
printf("List elements: ");
while (tempNode != NULL) {
printf("%d ", tempNode->data);
Editor is loading...