Friday, 4 November 2016

Program 14 - 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_end(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 = NULL;
last -> next = nn;
last = nn;
display();
}
}
void delete_end(){
struct node *prev = NULL, *delete_this;
int num;
if(start == NULL){
printf("Empty Linked List\n");
} else if(start -> next == NULL){
// Only one node
printf("%d deleted from Linked List\n", start -> data);
free(start);
free(last);
start = last = NULL;
display();
} else {
delete_this = start;
while(delete_this -> next != NULL){
prev = delete_this;
delete_this = delete_this -> next;
}
/* Now delete_this is at last position
* and prev is at second last position
*/
prev -> next = NULL;
last = prev;
printf("%d deleted from Linked List\n", delete_this -> data);
free(delete_this);
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, rpt = 1, num;
printf("***Create Linked List***\n");
create();
system("cls");
while(rpt != 0){
display();
printf("1. Insert at end\n2. Delete at end\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_end(num);
break;
case 2:
delete_end();
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