mirror of
https://github.com/Manoj-HV30/ds-lab-codes.git
synced 2026-05-16 19:35:22 +00:00
114 lines
2.0 KiB
C
114 lines
2.0 KiB
C
#include <stdbool.h>
|
|
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
|
|
struct Node {
|
|
struct Node *ptr;
|
|
int data;
|
|
};
|
|
|
|
struct Node *head = NULL;
|
|
|
|
struct Node *createNode(int v) {
|
|
struct Node *new = (struct Node *)malloc(sizeof(struct Node));
|
|
new->data = v;
|
|
new->ptr = NULL;
|
|
return new;
|
|
}
|
|
|
|
void insertend(int v, struct Node *new) {
|
|
if (head == NULL) {
|
|
head = new;
|
|
return;
|
|
}
|
|
struct Node *temp = head;
|
|
while (temp->ptr != NULL) {
|
|
temp = temp->ptr;
|
|
}
|
|
temp->ptr = new;
|
|
new->ptr = NULL;
|
|
}
|
|
|
|
void insertstart(int v, struct Node *new) {
|
|
struct Node *temp = head;
|
|
head = new;
|
|
new->ptr = temp;
|
|
}
|
|
|
|
void insert(int v, struct Node *new, int x) {
|
|
struct Node *temp = head;
|
|
int w = 0;
|
|
while (temp->ptr != NULL && w < x) {
|
|
temp = temp->ptr;
|
|
w++;
|
|
}
|
|
struct Node *temp2 = temp->ptr;
|
|
temp->ptr = new;
|
|
new->ptr = temp2;
|
|
}
|
|
void display() {
|
|
struct Node *temp = head;
|
|
while (temp != NULL) {
|
|
printf("%d \n", temp->data);
|
|
temp = temp->ptr;
|
|
}
|
|
}
|
|
void deletestart() {
|
|
if (head == NULL) {
|
|
printf("list empty");
|
|
return;
|
|
}
|
|
struct Node *temp = head;
|
|
|
|
head = temp->ptr;
|
|
free(temp);
|
|
}
|
|
void deletelast() {
|
|
if (head == NULL) {
|
|
printf("list empty");
|
|
return;
|
|
} else {
|
|
struct Node *temp = head;
|
|
struct Node *prev = NULL;
|
|
while (temp->ptr != NULL) {
|
|
prev = temp;
|
|
temp = temp->ptr;
|
|
}
|
|
prev->ptr = NULL;
|
|
free(temp);
|
|
}
|
|
}
|
|
|
|
void deletex(int x) {
|
|
if (head == NULL) {
|
|
printf("list empty");
|
|
return;
|
|
} else {
|
|
struct Node *temp = head;
|
|
struct Node *prev = NULL;
|
|
int k = 0;
|
|
while (temp->ptr != NULL && k < x - 1) {
|
|
prev = temp;
|
|
temp = temp->ptr;
|
|
k++;
|
|
}
|
|
// If x is beyond the last node
|
|
if (temp == NULL) {
|
|
printf("Position %d not found\n", x);
|
|
return;
|
|
}
|
|
prev->ptr = temp->ptr;
|
|
free(temp);
|
|
}
|
|
}
|
|
int main() {
|
|
struct Node *first = createNode(5);
|
|
insertstart(5, first);
|
|
display();
|
|
struct Node *second = createNode(6);
|
|
insertend(6, second);
|
|
display();
|
|
deletelast();
|
|
display();
|
|
}
|