Friday, 4 November 2016

Program 11 - Input Restricted Double Ended Queue



#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node *next;
};
struct node *start = NULL, *last = NULL;
void create(){
struct node *nn;
int num;
printf("Enter data or enter -1 to stop: ");
scanf("%d", &num);
while(num != -1) {
nn = (struct node *) malloc(sizeof(struct node));
nn -> data = num;
nn -> next = NULL;
if(start == NULL) {
start = 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;
nn = (struct node *) malloc(sizeof(struct node));
nn -> data = num;
nn -> next = NULL;
if(start == NULL) {
start = last = nn;
} else {
last -> next = nn;
last = nn;
}
}
void delete_beg() {
struct node *p;
if(start == NULL) {
printf("Deque Empty\n");
} else {
p = start;
start = start -> next;
free(p);
}
}
void delete_end(){
struct node *p, *q;
if(start == NULL) {
printf("Deque Empty\n");
} else if(start -> next == NULL) {
//Only one node
free(start);
start = last = NULL;
} else {
p = start;
q = NULL;
while(p -> next != NULL) {
q = p;
p = p -> next;
}
last = q;
last -> next = NULL;
free(p);
}
}
void display(){
struct node *p;
if(start == NULL) {
printf("Deque Empty\n");
} else {
printf("The deque is: \n");
p = start;
while(p != NULL) {
printf("%d ", p -> data);
p = p -> next;
}
}
printf("\n");
}
int main(){
int choice, num, rpt = 1;
printf("***Create Double Ended Queue\n");
create();
while(rpt != 0){
printf("1. Insert at End\n2. Delete from Beginning\n3. Delete from End\n4. Display\n5. Exit\n");
printf("--------------\n");
printf("Enter a choice: ");
scanf("%d", &choice);
switch(choice){
case 1:
printf("Enter num: ");
scanf("%d", &num);
insert_end(num);
display();
break;
case 2:
delete_beg();
display();
break;
case 3:
delete_end();
display();
break;
case 4:
display();
break;
case 5:
exit(0);
}
printf("Do you want to continue? (1/0): ");
scanf("%d", &rpt);
system("cls");
}
}














































































































































































































No comments:

Post a Comment