Friday, 4 November 2016

Program 13 - Linked List Operations



#include <stdio.h>
#include <stdlib.h>
struct node{
int data;
struct node *next;
};
struct node *start = NULL, *last = NULL;
void create(){
int num;
struct node *nn;
printf("Enter data: ");
scanf("%d", &num);
while(num != -1){
nn = (struct node *)malloc(sizeof(struct node));
nn -> data = num;
nn -> next = NULL;
if(start == NULL){
start = nn;
last = nn;
} else {
last -> next = nn;
last = nn;
}
printf("Enter data or enter -1 to stop: ");
scanf("%d", &num);
}
}
void insert_beg(int num){
struct node *nn;
if(start == NULL){
printf("Empty Linked List\n");
} else {
nn = (struct node *)malloc(sizeof(struct node));
nn -> data = num;
nn -> next = start;
start = nn;
display();
}
}
void delete_beg(){
struct node *p;
if(start == NULL){
printf("Empty Linked List\n");
} else {
p = start;
start = start -> next;
printf("%d deleted from Linked List\n", p -> data);
free(p);
display();
}
}
void display(){
struct node *p;
if(start == NULL){
printf("Empty Linked list\n");
} else {
p = start;
while(p != NULL){
printf("%d ->", p -> data);
p = p -> next;
}
printf("NULL\n");
}
}
int main(){
int choice, num, rpt = 1;
printf("***Create Linked List***\n");
create();
system("cls");
while(rpt != 0){
display();
printf("1. Insert at beginning\n2. Delete at beginning\n3. Display\n4. Exit\n");
printf("--------------\n");
printf("Enter a choice: ");
scanf("%d", &choice);
switch(choice){
case 1:
printf("Enter num: ");
scanf("%d", &num);
insert_beg(num);
break;
case 2:
delete_beg();
break;
case 3:
display();
break;
case 4:
exit(0);
}
printf("Do you want to continue? (1/0): ");
scanf("%d", &rpt);
system("cls");
}
}














































































































































































































No comments:

Post a Comment