How to do peek operation in queue in C? - c

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define max 100
int enqueue();
int dequeue();
int peek();
void display();
int main()
{
char name[max][80], data[80];
int front, rear, value;
int ch;
front = rear = -1;
printf("------------------------------\n");
printf("\tMenu");
printf("\n------------------------------");
printf("\n [1] ENQUEUE");
printf("\n [2] DEQUEUE");
printf("\n [3] PEEK");
printf("\n [4] DISPLAY");
printf("\n------------------------------\n");
while(1)
{
printf("Choice : ");
scanf("%d", &ch);
switch(ch)
{
case 1 : // insert
printf("\nEnter the Name : ");
scanf("%s",data);
value = enqueue(name, &rear, data);
if(value == -1 )
printf("\n QUEUE is Full \n");
else
printf("\n'%s' is inserted in QUEUE.\n\n",data);
break;
case 2 : // delete
value = dequeue(name, &front, &rear, data);
if( value == -1 )
printf("\n QUEUE is Empty \n");
else
printf("\n Deleted Name from QUEUE is : %s\n", data);
printf("\n");
break;
case 3:
value = peek(name, &front, &rear, data);
if(value != -1)
{
printf("\n The front is: %s", value);
}
break;
case 5 : exit(0);
default: printf("Invalid Choice \n");
}
}
return 0;
}
int enqueue(char name[max][80], int *rear, char data[80])
{
if(*rear == max -1)
return(-1);
else
{
*rear = *rear + 1;
strcpy(name[*rear], data);
return(1);
}
}
int dequeue(char name[max][80], int *front, int *rear, char data[80])
{
if(*front == *rear)
return(-1);
else
{
(*front)++;
strcpy(data, name[*front]);
return(1);
}
}
int peek(char name[max][80], int *front, int *rear, char data[80])
{
if(*front == -1 || *front > *rear)
{
printf(" QUEUE IS EMPTY\n");
return -1;
}
else
{
return data[*front];
}
}
My Peek operation has a problem it does not print the first element.
For example, the user input one name, and when the user selects the peek operation, the program should print the first element, but my program always prints QUEUE IS EMPTY even though my queue is not empty.
The peek operation should print the first element of the queue.

If you enqueue() then peek() the variable front is still -1 and it incorrectly says the queue is empty.
I suggest your treat front to rear as a half open interval with both initialized to 0, so it's empty if *front == *rear.
peek() need to populate data and return an integer (not data[*front] which is nonsense).
main() after peek() you need to print data not value.
Your prototypes are wrong. If you move the functions before main() then you can remove them.
int enqueue(char name[max][80], int *rear, const char data[80]) {
if(*rear + 1 == max)
return -1;
strcpy(name[*rear], data);
(*rear)++;
return 1;
}
int peek(char name[max][80], int *front, int *rear, char data[80]) {
if(*front == *rear) {
printf(" QUEUE IS EMPTY\n");
return -1;
}
strcpy(data, name[*front]);
return 1;
}
// ...
int main() {
char name[max][80], data[80];
int front = 0;
int rear = 0;
int value;
int ch;
printf("------------------------------\n");
printf("\tMenu");
printf("\n------------------------------");
printf("\n [1] ENQUEUE");
printf("\n [2] DEQUEUE");
printf("\n [3] PEEK");
printf("\n [4] DISPLAY");
printf("\n------------------------------\n");
while(1)
{
printf("Choice : ");
scanf("%d", &ch);
switch(ch) {
case 1 : // insert
printf("\nEnter the Name : ");
scanf("%s",data);
value = enqueue(name, &rear, data);
if(value == -1 )
printf("\n QUEUE is Full \n");
else
printf("\n'%s' is inserted in QUEUE.\n\n",data);
break;
case 2 : // delete
value = dequeue(name, &front, &rear, data);
if( value == -1 )
printf("\n QUEUE is Empty \n");
else
printf("\n Deleted Name from QUEUE is : %s\n", data);
printf("\n");
break;
case 3:
value = peek(name, &front, &rear, data);
if(value != -1)
{
printf("\n The front is: %s\n", data);
}
break;
case 5 : exit(0);
default: printf("Invalid Choice \n");
}
}
return 0;
}
example session:
------------------------------
Menu
------------------------------
[1] ENQUEUE
[2] DEQUEUE
[3] PEEK
[4] DISPLAY
------------------------------
Choice : 1
Enter the Name : test
'test' is inserted in QUEUE.
Choice : 3
The front is: test

Related

how to display all elements in queue?

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define max 100
char name[max][80], data[80];
int front = 0;
int rear = 0;
int enqueue();
int dequeue();
int peek();
void display();
int main() {
int value;
int ch;
printf("------------------------------\n");
printf("\tMenu");
printf("\n------------------------------");
printf("\n [1] ENQUEUE");
printf("\n [2] DEQUEUE");
printf("\n [3] PEEK");
printf("\n [4] DISPLAY");
printf("\n------------------------------\n");
while(1)
{
printf("Choice : ");
scanf("%d", &ch);
switch(ch) {
case 1 : // insert
printf("\nEnter the Name : ");
scanf("%s",data);
value = enqueue(name, &rear, data);
if(value == -1 )
printf("\n QUEUE is Full \n");
else
printf("\n'%s' is inserted in QUEUE.\n\n",data);
break;
case 2 : // delete
value = dequeue(name, &front, &rear, data);
if( value == -1 )
printf("\n QUEUE is Empty \n");
else
printf("\n Deleted Name from QUEUE is : %s\n", data);
printf("\n");
break;
case 3:
value = peek(name, &front, &rear, data);
if(value != -1)
{
printf("\n The front is: %s\n", data);
}
break;
case 4:
display();
break;
case 5 : exit(0);
default: printf("Invalid Choice \n");
}
}
return 0;
}
int enqueue(char name[max][80], int *rear, const char data[80]) {
if(*rear + 1 == max)
return -1;
strcpy(name[*rear], data);
(*rear)++;
return 1;
}
int dequeue(char name[max][80], int *front, int *rear, char data[80])
{
if(*front == *rear)
return -1;
strcpy(data, name[(*front)++]);
return 1;
}
int peek(char name[max][80], int *front, int *rear, char data[80]) {
if(*front == *rear) {
printf(" QUEUE IS EMPTY\n");
return -1;
}
strcpy(data, name[*front]);
return 1;
}
void display(char name[max][80], int *front, int *rear, char data[80])
{
if(*front == -1 || *front > *rear)
{
printf("\n QUEUE IS EMPTY");
}
else
{
for(int i = *front; i<= *rear; i++)
{
printf("\t %s",data[i]);
}
}
}
Student here.
I need to display all elements inside the queue, but my program ends whenever I click option number 4, For example, the user inputs four names, "Jennie, Lisa, Jisoo, Rose", when the user selects option number 4, the program should print all 4 names. Even though I only input one name and need to print it, the program just ends. How to fix this?
I provided similar advise on earlier questions:
Your prototypes are incorrect (either fix them or delete them and move the definitions before use). I removed the prototype of display() and moved the implementation before use.
As your prototypes are wrong your compiler doesn't complain when you call dislay() without arguments (yours requires 4 arguments).
As display() doesn't change name, front, or rear I suggest you make first one const, and the other two integers. data is not used so eliminate it.
display(): queue is empty if front and rear have the same value.
Eliminate the global variables in favor of local variables in main().
Here is your working program:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define max 100
char name[max][80], data[80];
int front = 0;
int rear = 0;
int enqueue();
int dequeue();
int peek();
void display(const char name[max][80], int front, int rear) {
if(front == rear) {
printf("\n QUEUE IS EMPTY");
return;
}
for(int i = front; i < rear; i++)
{
printf("\t %s", name[i]);
}
printf("\n");
}
int main() {
int value;
int ch;
printf("------------------------------\n");
printf("\tMenu");
printf("\n------------------------------");
printf("\n [1] ENQUEUE");
printf("\n [2] DEQUEUE");
printf("\n [3] PEEK");
printf("\n [4] DISPLAY");
printf("\n------------------------------\n");
while(1)
{
printf("Choice : ");
scanf("%d", &ch);
switch(ch) {
case 1 : // insert
printf("\nEnter the Name : ");
scanf("%s",data);
value = enqueue(name, &rear, data);
if(value == -1 )
printf("\n QUEUE is Full \n");
else
printf("\n'%s' is inserted in QUEUE.\n\n",data);
break;
case 2 : // delete
value = dequeue(name, &front, &rear, data);
if( value == -1 )
printf("\n QUEUE is Empty \n");
else
printf("\n Deleted Name from QUEUE is : %s\n", data);
printf("\n");
break;
case 3:
value = peek(name, &front, &rear, data);
if(value != -1)
{
printf("\n The front is: %s\n", data);
}
break;
case 4:
display(name, front, rear);
break;
case 5 : exit(0);
default: printf("Invalid Choice \n");
}
}
return 0;
}
int enqueue(char name[max][80], int *rear, const char data[80]) {
if(*rear + 1 == max)
return -1;
strcpy(name[*rear], data);
(*rear)++;
return 1;
}
int dequeue(char name[max][80], int *front, int *rear, char data[80])
{
if(*front == *rear)
return -1;
strcpy(data, name[(*front)++]);
return 1;
}
int peek(char name[max][80], int *front, int *rear, char data[80]) {
if(*front == *rear) {
printf(" QUEUE IS EMPTY\n");
return -1;
}
strcpy(data, name[*front]);
return 1;
}
and sample session:
------------------------------
Menu
------------------------------
[1] ENQUEUE
[2] DEQUEUE
[3] PEEK
[4] DISPLAY
------------------------------
Choice : 1
Enter the Name : test
'test' is inserted in QUEUE.
Choice : 1
Enter the Name : test2
'test2' is inserted in QUEUE.
Choice : 4
test test2

C simple queue code stuck running while inserting

/* Queues */
/* Linear Queues */
#include <stdio.h>
#define MAX 10
int queue[MAX];
int rear=-1;front=-1;
void insert(void);
int delete_element(void);
int peek(void);
void display(void);
int main(){
int option;
printf("\n\n ***** MAIN MENU *****");
printf("\n 1. Insert an element");
printf("\n 2. Delete an element");
printf("\n 3. Peek");
printf("\n 4. Display the queue");
printf("\n 5. EXIT");
printf("\n Enter your option : ");
scanf("%d", &option);
switch(option){
case 1:
insert();
break;
case 2:
int val;
val = delete_element();
if(val != -1)
printf("\n The number deleted is :%d", val);
break;
case 3:
val = peek();
if(val != -1)
printf("\n the first value in queue is: %d", val);
break;
case 4:
display();
break;
}while(option !=5);
return 0;
}
void insert(){
int num;
printf("\n Enter the number to be inserted in the queue : ");
scanf("%d", &num);
if (rear == MAX-1){
printf("Queue is full");
}
else if(front == -1 && rear == -1){
front = rear = 0; /* If queue is empty, set front and rear to 0 */
}
else{
rear++; /* Increment rear */
queue[rear] = num;
}
}
int delete_element(){
int val;
if(front == -1 || front>rear){
printf("Queue is empty");
return -1;
}
else{
val=queue[front];
front++;
if(front>rear){
front = rear = -1; /* Front > rear = queue empty */
}
return val; /* Return popped value */
}
}
int peek(){
if(front == -1 || front>rear){
printf("Queue is empty");
return -1;
}
else{
return queue[front];
}
}
void display(){
int i;
printf("\n");
if(front == -1 || front>rear){
printf("Queue is empty");
}
else{
for(i=front;i<=rear;i++){
printf("\t %d",&queue[i]);
}
}
}
Code gets stuck while I try to insert element "3".
I am following Data Structures using C book, so I am not sure they would write a broken code to the book, but this just boggled my mind. It is running for 4 minutes, without doing literally anything. Neither deleting, peeking, inserting, displaying everything gets stuck in a loop.
You have the code (abbreviated):
switch(option){
...
}while(option !=5);
Slightly reformatted it's the same as:
switch(option){
...
}
while(option !=5)
{
}
That is, your switch ends and then you have an infinite loop.
I'll guess you really wanted to do an do-while loop around the menu and switch:
do
{
// Print menu
// Get input
// Switch
} while (option != 5);

queue of structs in C language

I am trying to create a simple program in C language using queues and structs .... to be a ticketing system.
ticket includes:
ticket id (to search with)
name
age
favorite movie
options to choose from:
add new ticket (enqueue)
search and display one ticket
Delete all (empty queue)
Display all tickets
my code:
#include <stdio.h>
#define SIZE 100
void enQueue(int);
void deQueue();
void display();
void search();
struct ticket_details
{
int ticket_id;
char name[20];
int age;
char movie[50];
};
struct ticket_details ticket_details;
int items[SIZE];
int front = -1;
int rear = -1;
int ticket_number=0;
int search_number=0;
void main() {
int choice = 0;
printf("1-buy ticket\n2-search for a ticket\n3-display all tickets\n4-delete a ticket\n");
scanf("%d",&choice);
switch(choice) {
case '1' :
ticket_number++;
enQueue(ticket_number);
break;
case '2' :
printf("ticket number:");
scanf("%d",&search_number);
search(search_number);
case '3' :
printf("display all tickets\n");
display();
break;
case '4' :
printf("ticket number:\n");
scanf("%d",&ticket_number);
deQueue(ticket_number);
break;
default :
printf("Invalid choice\n" );
}
}
void enQueue(int value) {
if (rear == SIZE - 1)
printf("\nNo more tickets!!");
else {
if (front == -1)
front = 0;
rear++;
items[rear] = value;
printf("Name:");
scanf("%s",ticket_details[value].name);
printf("age:");
scanf("%d",&ticket_details[items[rear]].age);
printf("Movie:");
scanf("%s",ticket_details[items[rear]].movie);
}
}
void deQueue(int value) {
if (front == -1)
printf("\nNo tickets to delete");
else {
int i;
for (i = front; i <= rear; i++)
if(i==value)
free(value);
printf("\nDeleted : %d", ticket_details[front]);
}
}
// Function to print the queue
void display() {
if (rear == -1)
printf("\nNo tickets found");
else {
int i;
printf("\nAll tickets:\n");
for (i = front; i <= rear; i++)
printf("%d/n", &ticket_details[i].ticket_id+
"%s/n",ticket_details[i].name+
"%d/n",ticket_details[i].age+
"%s/n",ticket_details[i].movie);
}
printf("\n");
}
void search(int search_number) {
int i;
for (i = front; i <= rear; i++)
if(i==search_number)
printf("%d/n", &ticket_details[search_number].ticket_id+
"%s/n",ticket_details[search_number].name+
"%d"/n,ticket_details[search_number].age+
"%s"/n,ticket_details[search_number].movie);
else
{
printf("Ticket number not found");
}
}

C Thread bad access error when input string (link list)

I have been getting Thread 1 : EXC_BAD_ACCESS error when trying to push a string element into the stack. I've changed the char* name to char name[21] but the assignment char[21] is not assignable to curr->name. Also I've tried fgets but the error still there. Anyone know where the error?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct parts
{
char* name;
char* type;
int quantity;
int price;
int num;
struct parts * next;
}*head,*tail,*curr,komponen;
void menu();
void show_Parts();
void push(char* nm, char* tip, int jml, int harga, int nom);
void del();
int main() {
menu();
del();
getchar();
return 0;
}
void push(char* nm, char* tip, int jml, int harga, int nom)
{
// 1.
curr = (struct parts *)malloc(sizeof(struct parts));
// 2.
if (curr == NULL) {
exit(0);
}
head = NULL;
head = curr->next;
curr->name = nm;
curr->type = tip;
curr->quantity = jml;
curr->price = harga;
curr->num = nom;
curr = head;
//
printf("Input name of the new item [3..20]: ");
scanf("%s",nm);
if (strlen(nm) < 3 || strlen(nm) > 20) {
printf("Length of name must between 3 and 20");
exit(0);
}
printf("Input type of the new item [processor/graphic card/memory]: ");
scanf("%s",tip);
if (tip != "processor" || tip != "graphic card" || tip != "memory") {
printf("Input type of existing item. Error");
exit(0);
}
printf("Input quantity of the new item [1..20]: ");
scanf("%d",&jml);
if (jml < 1 || jml > 20) {
printf("Quantity between 1 and 20\n");
exit(0);
}
printf("Input price of new item [$1..$1000]: ");
scanf("%d",&harga);
if (harga < 1 || harga > 1000) {
printf("Price between 1 and 1000\n");
exit(0);
}
nom++;
printf("--- Add New Item Success ---\n");
tail->next = NULL;
}
void del()
{
if (curr == NULL) {
exit(0);
}
curr = head;
head = head->next;
free(curr);
}
void menu()
{
int choic;
do {
printf("BLUE COMPUTER ADMINISTRATOR\n");
printf("++++++++++++++++++++++++++++\n");
printf("1. Item list\n");
printf("2. Add <PUSH> New item\n");
printf("3. Exit\n");
printf(">> Input your choice : ");
switch (choic) {
case 1:
show_Parts();
break;
case 2:
push(komponen.name,komponen.type,komponen.price, komponen.quantity, komponen.num);
break;
case 3:
del();
exit(0);
break;
}
scanf("%d",&choic);
} while (choic != 3);
}
void show_Parts()
{
if (curr == NULL) {
printf("No item in list\n");
exit(0);
}
printf(" ---- ITEM LIST ---- \n\n");
printf("-----+------------------+--------+-----------+--------\n");
printf("|No. | Name | Type | Quantity | Price|\n");
do {
printf("|%d |%s |%s |%d |%d \n",curr->num, curr->name, curr->type, curr->quantity, curr->price);
curr = curr->next;
}while (curr != NULL);
}
Thanks.

Passing pointers between functions in an implementation of linked list

The problem was solved. A guy gave it in comments. The problem was that I was using %d to read in a short int. I should have used %hd or I should have used an `int'.
I tried to create a program of singly-linked list using only local variables. I was able to make a working program by using global variables.
The program with local variables compiles but it crashes when I try to traverse the linked list.
I have absolutely no idea what is wrong with the implementation with local variables. What is the problem present in the Implementation with local variables?
ABOUT THE STRUCTURE OF THE PROGRAMS:
I understand that the programs are big so I'll put in something about structure of the program.
The program is structured as a menu driven program. So the initial calls to functions are in main() function
There are 3 options in main() menu - exit, traverse and insertion
Exit returns 0 to exit program while other 2 do function calls
Insertion function itself is arranged as menu-driven program.
It has 3 options - return , insert_begin and insert_end. The last 2 are function calls.
I know there are memory leaks as I haven't freed any memory but I will take care of that after I can understand the problem in the current program.
//WORKING IMPLEMENTATION USING GLOBAL VARIABLE
#include<stdio.h>
#include<stdlib.h>
#define MIN 0
#define MAX 2
#define INS_MIN 0
#define INS_MAX 2
typedef struct node
{
int data;
struct node *next;
}sll_node;
sll_node *start = NULL;
void intro()
{
system("cls");
printf("\n\tThese are the various options:\n");
printf("\n\t00 Exit");
printf("\n\t01 Traverse the list");
printf("\n\t02 Insertion into the list");
}
void insert_begin()
{
sll_node *node = malloc(sizeof(sll_node));
if(node == NULL)
{
printf("\n\tNot enough menory");
exit(-1);
}
int data;
printf("\n\tData to be entered: ");
scanf("%d", &data);
node->data = data;
node-> next = start;
start = node;
}
void insert_end()
{
sll_node *node = malloc(sizeof(sll_node));
if(node == NULL)
{
printf("\n\tNot enough menory");
exit(-2);
}
if(start == NULL)
insert_begin();
else
{
printf("\n\tData to be entered: ");
scanf("%d", &(node->data));
node-> next = NULL;
sll_node *node2;
for(node2 = start; node2->next != NULL; node2 = node2->next)
;
node2->next = node;
}
}
void insert_intro()
{
system("cls");
printf("\n\tThese are the various options:\n");
printf("\n\t00 Insertion Done");
printf("\n\t01 Insert at beginning");
printf("\n\t02 Insert at end");
}
void insertion()
{
short choice;
while(1)
{
choice = -1;
while(choice < INS_MIN || choice > INS_MAX)
{
insert_intro();
printf("\n\n\tEnter your chocie: ");
scanf("%d", &choice);
}
switch(choice)
{
case 0:
return;
case 1:
insert_begin();
break;
case 2:
insert_end();
break;
}
}
}
void traverse()
{
if(start == NULL)
printf("\n\n\tLinked list is empty");
else
{
printf("\n\n\t");
for(sll_node *node = start; node != NULL; node = node->next)
printf("%d ", node->data);
}
getch();
}
int main()
{
short choice;
while(1)
{
choice = -1;
while(choice < MIN || choice > MAX)
{
intro();
printf("\n\n\tEnter your choice: ");
scanf("%d", &choice);
}
switch(choice)
{
case 0:
return 0;
case 1:
traverse();
break;
case 2:
insertion();
break;
}
}
return 0;
}
//COMPILES BUT CRASHES - Same program but with local variable start and variable passing between functions
#include<stdio.h>
#include<stdlib.h>
#define MIN 0
#define MAX 2
#define INS_MIN 0
#define INS_MAX 2
typedef struct node
{
int data;
struct node *next;
}sll_node;
void intro()
{
system("cls");
printf("\n\tThese are the various options:\n");
printf("\n\t00 Exit");
printf("\n\t01 Traverse the list");
printf("\n\t02 Insertion into the list");
}
sll_node* insert_begin(sll_node *start)
{
sll_node *node = malloc(sizeof(sll_node));
if(node == NULL)
{
printf("\n\tNot enough menory");
exit(-1);
}
int data;
printf("\n\tData to be entered: ");
scanf("%d", &data);
node->data = data;
node-> next = start;
return node;
}
sll_node* insert_end(sll_node *start)
{
sll_node *node = malloc(sizeof(sll_node));
if(node == NULL)
{
printf("\n\tNot enough menory");
exit(-2);
}
if(start == NULL)
start = insert_begin(start);
else
{
printf("\n\tData to be entered: ");
scanf("%d", &(node->data));
node-> next = NULL;
sll_node *node2;
for(node2 = start; node2->next != NULL; node2 = node2->next)
;
node2->next = node;
}
return start;
}
void insert_intro()
{
system("cls");
printf("\n\tThese are the various options:\n");
printf("\n\t00 Insertion Done");
printf("\n\t01 Insert at beginning");
printf("\n\t02 Insert at end");
}
sll_node* insertion(sll_node *start)
{
short choice;
while(1)
{
choice = -1;
while(choice < INS_MIN || choice > INS_MAX)
{
insert_intro();
printf("\n\n\tEnter your chocie: ");
scanf("%d", &choice);
}
switch(choice)
{
case 0:
return start;
case 1:
start = insert_begin(start);
break;
case 2:
start = insert_end(start);
break;
}
}
}
void traverse(sll_node *start)
{
if(start == NULL)
printf("\n\n\tLinked list is empty");
else
{
printf("\n\n\t");
for(sll_node *node = start; node != NULL; node = node->next)
printf("%d ", node->data);
}
getch();
}
int main()
{
sll_node *start = NULL;
short choice;
while(1)
{
choice = -1;
while(choice < MIN || choice > MAX)
{
intro();
printf("\n\n\tEnter your choice: ");
scanf("%d", &choice);
}
switch(choice)
{
case 0:
return 0;
case 1:
traverse(start);
break;
case 2:
start = insertion(start);
break;
}
}
return 0;
}
You are not returning anything from insertion() function when item is added to a list. So linked list may not get constructed properly.
Probably, you should return start only when its added at the beginning, otherwise start in main() will not point to head of the list.
sll_node* insertion(sll_node *start)
{
...
switch(choice)
{
case 0:
return start;
case 1:
start = insert_begin(start);
return start; //<----- return node
break;
case 2:
start = insert_end(start);
break;
}
...
}
Change short choice to int choice.
Why does this make a difference?
Short answer is that printf("%d") expects an integer.
The long answer is "%d" describes the data type you are passing to printf as an integer (which is commonly 4 to 8 bytes), and you're giving it a datatype of short - which is commonly 2 bytes long. When your program reads the input and stores it at the pointer, &choice, it writes 4 bytes starting at that address (but only 2 were reserved). This causes a segmentation fault and will crash your program.
Here's a list to some printf documentation. You'll notice that to pass a short to printf you would write %hd instead of %d
When i compile your code on my computer, it works, but i changed "short choice" to "int choice", because scanf("%d", &choice) takes 4 bytes to write on, and when choice is short it crashes, because short has only 2 bytes, therefore stack corruption will occur, my be on your computer this corruption damage the "start" pointer.
About the crash. Change the argument start in both functions insert_begin and insert_end to sll_node ** start, and when assigning new value, use the expression *start = your-new-value. It is because you have to pass a pointer to the local variable start which is also pointer. You do not need to change function traverse.
About memory leaks, let me to point-out that when you call insert_begin from inside insert_end, the node created from insert_end is left unused. before exit() and the return in main() you should free the list.
Yes, sorry. There was another bug hard to see. It was at 2 lines where you read (choice).
short choice;
...
// It is ERROR to use "%d" with (short choice), because the stack will
// be overwritten with unsuspected results. The format specifier "%hd"
// say to compiler that (&choice) point to a short 16-bit integer,
// not 32-bit
scanf("%hd", &choice);
This is slightly different version, tested, without memory leaks.
//
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#define MIN 0
#define MAX 2
#define INS_MIN 0
#define INS_MAX 2
typedef struct node
{
int data;
struct node *next;
} sll_node;
void clear_list(sll_node** start)
{
assert(start != NULL);
sll_node* node = *start;
while (node != NULL)
{
sll_node* element = node;
node = element->next;
free(element);
}
*start = NULL;
}
void intro()
{
system("cls");
printf("\n\tThese are the various options:\n");
printf("\n\t00 Exit");
printf("\n\t01 Traverse the list");
printf("\n\t02 Insertion into the list");
}
void insert_begin(sll_node** pstart)
{
sll_node* node = (sll_node*)malloc(sizeof(sll_node));
if (node == NULL)
{
printf("\n\tNot enough menory");
clear_list(pstart);
exit(-1);
}
int data;
printf("\n\tData to be entered: ");
scanf_s("%d", &data);//scanf
node->data = data;
node->next = *pstart;
// update the local variable start passed from main to point just inserted node
*pstart = node;
}
void insert_end(sll_node** start)
{
assert(start != NULL);
if (*start == NULL)
{
insert_begin(start);
}
else
{
sll_node* node = (sll_node*)malloc(sizeof(sll_node));
if (node == NULL)
{
printf("\n\tNot enough menory");
clear_list(start);
exit(-2);
}
printf("\n\tData to be entered: ");
scanf("%d", &(node->data));
node->next = NULL;
sll_node* node2;
for(node2 = *start; node2->next != NULL; node2 = node2->next)
;
node2->next = node;
}
}
void insert_intro()
{
system("cls");
printf("\n\tThese are the various options:\n");
printf("\n\t00 Insertion Done");
printf("\n\t01 Insert at beginning");
printf("\n\t02 Insert at end");
}
void insertion(sll_node** start)
{
short choice;
while(1)
{
choice = -1;
while(choice < INS_MIN || choice > INS_MAX)
{
insert_intro();
printf("\n\n\tEnter your chocie: ");
scanf("%hd", &choice);
}
switch(choice)
{
case 0:
return;
case 1:
insert_begin(start);
break;
case 2:
insert_end(start);
break;
}
}
}
void traverse(sll_node *start)
{
if (start == NULL)
printf("\n\n\tLinked list is empty");
else
{
printf("\n\n\t");
for(sll_node *node = start; node != NULL; node = node->next)
printf("%d ", node->data);
}
getch();
}
int main()
{
sll_node *start = NULL;
short choice;
while(1)
{
choice = -1;
while(choice < MIN || choice > MAX)
{
intro();
printf("\n\n\tEnter your choice: ");
scanf("%hd", &choice);
}
switch(choice)
{
case 0:
clear_list(&start);
return 0;
case 1:
traverse(start);
break;
case 2:
insertion(&start);
break;
}
}
return 0;
}
P.S. Very hard to edit! I'm new here and do not have enough experience. Wasted a lot of time to edit!

Resources