0% found this document useful (0 votes)
7 views3 pages

List Adt

Uploaded by

ebinarul177
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views3 pages

List Adt

Uploaded by

ebinarul177
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

#ifndef LISTHEADER_H_INCLUDED

#define LISTHEADER_H_INCLUDED

#include <stdio.h>
#include <stdlib.h>

struct Node {
int element;
struct Node *next;
};

typedef struct Node* List;


typedef struct Node* Position;

List create_header() {
List L = (List)malloc(sizeof(struct Node));
if (L != NULL) {
L->element = -1;
L->next = NULL;
}
return L;
}

Position find_pos(List L, int x) {


while (L != NULL && L->element != x) {
L = L->next;
}
return L;
}

void insert(List L, int x, Position p) {


if (p != NULL) {
Position tmp = (Position)malloc(sizeof(struct Node));
if (tmp != NULL) {
tmp->element = x;
tmp->next = p->next;
p->next = tmp;
} else {
printf("Out of space\n");
}
}
}

Position find_prev(List L, int x) {


while (L->next != NULL && L->next->element != x) {
L = L->next;
}
return L;
}

void delete(List L, int x) {


Position prev = find_prev(L, x);
if (prev->next != NULL) {
Position tmp = prev->next;
prev->next = tmp->next;
free(tmp);
} else {
printf("Element not found\n");
}
}

void display(List L) {
if (L->next == NULL) {
printf("Singly linked list is empty\n");
} else {
printf("The elements in the singly linked list are:\n");
for (L = L->next; L != NULL; L = L->next) {
printf("%d --> ", L->element);
}
printf("NULL\n"); // Indicate the end of the list
}
}

#endif // LISTHEADER_H_INCLUDED

#include <stdio.h>
#include <stdlib.h>
#include "listheader.h"

int main() {
int choice, prev, x, y;
Position prev_pos;
List l = create_header();

printf("Linked List Operations:");


printf("\n1. Insert \n2. Delete \n3. Display \n4. Exit\n");

do {
printf("\nEnter your choice: ");
scanf("%d", &choice);

switch(choice) {
case 1:
printf("Enter the element after which to insert: ");
scanf("%d", &prev);
prev_pos = find_pos(l, prev);
if (prev_pos == NULL)
printf("Element not found\n");
else {
printf("Enter the element to insert: ");
scanf("%d", &x);
insert(l, x, prev_pos);
}
break;

case 2:
printf("Enter the element to be deleted: ");
scanf("%d", &y);
delete(l, y);
break;

case 3:
display(l);
break;

case 4:
printf("Exiting...\n");
break;

default:
printf("Invalid choice. Please try again.\n");
}
} while (choice != 4);

return 0;
}

You might also like