im doing a project, where i need to manage a queue of sorts, specifically cars in a car wash. I've found some code online, that allows you to add to queue and manage it, with integer inputs. Is there a way for me to re-write this code, so that it accepts inputs as c strings instead of integers?
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *next;
};
struct node *front = NULL;
struct node *rear = NULL;
void display();
void enqueue(int);
void dequeue();
int main()
{
int n, ch;
do
{
printf("\n\nQueue Menu\n1. Add \n2. Remove\n3. Display\n0. Exit");
printf("\nEnter Choice 0-3? : ");
scanf("%d", &ch);
switch (ch)
{
case 1:
printf("\nEnter number ");
scanf("%d", &n);
enqueue(n);
break;
case 2:
dequeue();
break;
case 3:
display();
break;
}
}while (ch != 0);
}
void enqueue(int item)
{
struct node *nptr = malloc(sizeof(struct node));
nptr->data = item;
nptr->next = NULL;
if (rear == NULL)
{
front = nptr;
rear = nptr;
}
else
{
rear->next = nptr;
rear = rear->next;
}
}
void display()
{
struct node *temp;
temp = front;
printf("\n");
while (temp != NULL)
{
printf("%d\t", temp->data);
temp = temp->next;
}
}
void dequeue()
{
if (front == NULL)
{
printf("\n\nqueue is empty \n");
}
else
{
struct node *temp;
temp = front;
front = front->next;
printf("\n\n%d deleted", temp->data);
free(temp);
}
}
Where the desired input would be one of these strings;
AV96888 VW alm
KD65656 Audi luksus
AX21878 Ford alm
CN32323 VW alm
NB21214 Ford luksus
UM21878 Ford alm
AV54361 Tesla luksus
Yes, the data is stored in the node:
struct node
{
int data;
struct node *next;
};
So you just need to change the int data; to a string.
Are there a reason you are doing this in C and not c++ ? There, string management is easier.
Here is the answer, you just convert the data to char * and use strdup to store the pointer
#include "stdlib.h"
#include "stdio.h"
#include "string.h"
struct node
{
char *data;
struct node *next;
};
struct node *front = NULL;
struct node *rear = NULL;
void enqueue(char *item)
{
struct node *nptr = malloc(sizeof(struct node));
nptr->data = strdup(item);
nptr->next = NULL;
if (rear == NULL)
{
front = nptr;
rear = nptr;
}
else
{
rear->next = nptr;
rear = rear->next;
}
}
void display()
{
struct node *temp;
temp = front;
printf("\n");
while (temp != NULL)
{
printf("%s\t", temp->data);
temp = temp->next;
}
}
void dequeue()
{
if (front == NULL)
{
printf("\n\nqueue is empty \n");
}
else
{
struct node *temp;
temp = front;
front = front->next;
printf("\n\n%d deleted", temp->data);
free(temp->data);
free(temp);
}
}
int main()
{
int ch;
char n[256];
do {
printf("\n\nQueue Menu\n1. Add \n2. Remove\n3. Display\n0. Exit");
printf("\nEnter Choice 0-3? : ");
scanf("%d", &ch);
switch (ch)
{
case 1:
printf("\nEnter a name: ");
scanf("%s", n);
enqueue(n);
break;
case 2:
dequeue();
break;
case 3:
display();
break;
}
}while (ch != 0);
}
Related
The program is not complete. I can add enqueue nodes, display the list of nodes, and find the top of the node, etc... But when I try to dequeue and return a node from the dequeue function the customer's name gets jumbled up. This is a queue implementation in linked list. The application is similar to an order system from a fast-food chain.
Also, I was expected to have this operation in my program:
"INIT(): creates and returns an empty queue."
Did I do it right?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXLENGTH 20
struct Node{
char name[MAXLENGTH];
char order[MAXLENGTH];
struct Node* link;
};
struct Node* Init();
int Empty(struct Node*, struct Node*);
struct Node* Front(struct Node*);
void AskOrder(struct Node**, struct Node**);
void EnQueue(char*, char* , struct Node** , struct Node** );
struct Node* DeQueue(struct Node**, struct Node** );
void display(struct Node* );
int main()
{
struct Node* front = NULL;
struct Node* rear = NULL;
int ch = -1;
struct Node* printme = NULL;
while(ch!=0)
{
printf("ORDER LIST:");
if (Empty(front, rear) != 1)
display(front);
printf("\n\nJohn's Store Menu:\n"
"\n [1] Fall in line"
"\n [2] Serve order"
"\n [3] Next order"
"\n [4] Closing time"
"\n [0] Exit\n"
"\nEnter choice: ");
scanf("%d", &ch);
switch(ch)
{
case 1:
AskOrder(&front, &rear);
break;
case 2:
if(Empty(front, rear) != 1)
{
printme = DeQueue(&front, &rear);
printf("\nNow serving [%s] to customer [%s].\n", printme->order, printme->name);
}else
printf("The QUEUE is EMPTY. No orders to serve.");
break;
case 3:
if(Empty(front, rear) != 1)
{
printme = Front(front);
printf("\nNext order: [%s] of customer [%s].\n", printme->order, printme->name);
}else
printf("The QUEUE is EMPTY. No orders to serve.\n");
break;
case 4:
if(Empty(front, rear) != 1)
{
}else
printf("The QUEUE is EMPTY. No orders to serve.\n");
break;
case 0:
printf("\nOrder system has been terminated.\n");
return 0;
default:
printf("Invalid choice.\n");
break;
}
system("pause");
system("cls");
}
}
struct Node* Init()
{
struct Node* q = (struct Node*)malloc(sizeof(struct Node));
q->link = NULL;
return q;
}
int Empty(struct Node* fr, struct Node* rr)
{
if(fr == NULL && rr == NULL)
{
return 1;
}else{
return 0;
}
}
struct Node* Front(struct Node* fr)
{
return fr;
}
void AskOrder(struct Node** front, struct Node** rear)
{
char name[MAXLENGTH];
char order[MAXLENGTH];
printf("\nWhat's your name? ");
fflush(stdin);
gets(name);
printf("What's your order? ");
fflush(stdin);
gets(order);
EnQueue(name, order, front, rear);
}
void EnQueue(char* nm, char* ordr, struct Node** fr, struct Node** rr)
{
struct Node* temp = Init();
strcpy(temp->name, nm);
strcpy(temp->order, ordr);
if(Empty(*fr, *rr) == 1)
{
*fr = *rr = temp;
return;
}
(*rr)->link = temp;
*rr = temp;
}
struct Node* DeQueue(struct Node** fr, struct Node** rr)
{
struct Node* printme = *fr;
struct Node* temp = *fr;
if(*fr == *rr){
*fr = *rr = NULL;
}else{
*fr = (*fr)->link;
}
free(temp);
return printme;
}
void display(struct Node* fr){
while(fr != NULL)
{
printf("\n[%s] of customer [%s]", fr->order, fr->name);
fr = fr->link;
}
}
In this programm, when I create a list then it creates list successfully. But when I try to print it the program is just displaying last two values of node. I debug many times and found (*temp)->next changes the start1 and start2 pointer. I'm unable to solve how temp pointer changes value in start1 and start2.
Compiler didn't produce any error or warning.
#include <stdio.h>
struct node {
int info;
struct node *next;
} *start1 = NULL, *start2 = NULL;
void create_node(struct node **s1);
void display(struct node **s);
void create_node(struct node **s1)
{
struct node *ptr = NULL, **temp = s1;
ptr = (struct node *)malloc(sizeof(struct node));
if (*s1 == NULL)
{
*s1 = ptr;
} else
{
while ((*temp)->next != NULL)
(*temp) = (*temp)->next;
(*temp)->next = ptr;
}
ptr->next = NULL;
printf("enter the value\n");
scanf("%d", &(ptr->info));
}
void display(struct node **s)
{
struct node **temp = s;
while ((*temp) != NULL)
{
printf("%d\t", (*temp)->info);
(*temp) = (*temp)->next;
}
}
void main()
{
int choice = 0;
while (1){
clrscr();
printf("enter your choice\n");
printf("enter 1 to create_node1\nenter 2 to create node 2 \nenter 3 to display node 1\nenter 4 to display node2\nenter 5 to exit\n");
printf("\n");
scanf("%d", &choice);
switch (choice)
{
case 1:
create_node(&start1);//correct//
break;
case 2:
create_node(&start2);
break;
case 3:
display(&start1);
getch();
break;
case 4:
display(&start2);
getch();
break;
case 5:
exit(1);
break;
default:
printf("invalid");
}
}
}
Use this
while ((*temp)->next != NULL) (*temp) = (*temp)->next;.
This will solve the problem.
Otherwise, the index out of memory is accessed and program crash.
So I'm having trouble getting my program to print both the strings I input, or however many you want to put in the list, it always prints out the last string inputted multiple times. I am sorry about all the commented out code, most of it you don't need to read.
#include<stdio.h>
#include<stdlib.h>
struct node{
char *data;
struct node *next;
}*head;
typedef struct node NODE;
// Function prototypes
void append(char myStr[]);
void add( char myStr[] );
//void addafter(char myStr[], int loc);
void insert(char myStr[]);
int delete(char myStr[]);
void display(struct node *r);
int count();
// main function
int main()
{
int i;
struct node *n;
head = NULL;
char myStr[50];
while(1)
{
printf("\nList Operations\n");
printf("===============\n");
printf("1.Insert\n");
printf("2.Display\n");
printf("3.Size\n");
printf("4.Delete\n");
printf("5.Exit\n");
printf("Enter your choice : ");
if(scanf("%d", &i) <= 0)
{
printf("Enter only an Integer\n");
exit(0);
}
else
{
switch(i)
{
case 1:
printf("Enter the name to insert : ");
scanf("%50s", myStr);
insert(myStr);
break;
case 2:
if(head == NULL)
{
printf("List is Empty\n");
}
else
{
printf("Name(s) in the list are : ");
}
display(n);
break;
case 3:
printf("Size of the list is %d\n",count());
break;
case 4:
if(head == NULL)
printf("List is Empty\n");
else
{
printf("Enter the myStrber to delete : ");
scanf("%50s",myStr);
if(delete(myStr))
printf("%s deleted successfully\n",myStr);
else
printf("%s not found in the list\n",myStr);
}
break;
case 5:
return 0;
default:
printf("Invalid option\n");
}
}
}
return 0;
}
// Function definitions
void append(char myStr[])
{
struct node *temp,*right;
temp = (struct node *)malloc(sizeof(struct node));
temp->data = myStr;
right=(struct node *)head;
while(right->next != NULL)
{
right = right->next;
}
right->next = temp;
right = temp;
right->next = NULL;
}
// adding a node to the beginning of the linked list
void add( char myStr[] )
{
struct node *temp;
temp =(struct node *)malloc(sizeof(struct node));
temp->data = myStr;
// only one node on the linked list
if (head == NULL)
{
head = temp;
head->next = NULL;
}
else
{
temp->next = head;
head = temp;
}
}
void insert(char myStr[])
{
int c = 0;
struct node *temp;
temp = head;
if(temp == NULL)
{
add(myStr);
}
else
{
append(myStr);
}
}
int delete(char myStr[])
{
struct node *temp, *prev;
temp = head;
while(temp != NULL)
{
if(temp->data == myStr)
{
if(temp == head)
{
head = temp->next;
head = (*temp).next;
free(temp);
return 1;
}
else
{
prev->next = temp->next;
free(temp);
return 1;
}
}
else
{
prev = temp;
temp = temp->next;
}
}
return 0;
}
void display(struct node *r)
{
r = head;
if(r == NULL)
{
return;
}
while(r != NULL)
{
printf("%s ", r->data);
r = r->next;
if(r == NULL)
{
printf("\nOur linked list is finished!");
}
}
printf("\n");
}
int count()
{
struct node *n;
int c = 0;
n = head;
while(n != NULL)
{
n = n->next;
c++;
}
return c;
}
The problem seems to be that myStr at main function is a char[], so it's content is overritten every time you insert data. Notice that struct node data field is a char*, it's just pointing to myStr address.
Hope this help!
Your program has only one place to write your input, myStr.
With each input, myStr is erased and a something else is written to myStr.
The data member of all of the nodes, points to myStr. myStr will only contain the last input.
The display() function asks each node what is data. data points to myStr so each node prints the contents of myStr. myStr will only contain the last input so all the nodes print the last input.
To fix this, in the add() and append() functions, you need to give the data member some memory by using malloc(). Then copy the contents of myStr to the data member by using strcpy().
temp->data = malloc ( strlen ( myStr) + 1);
strcpy ( temp->data, myStr);
Do this instead of temp->data = myStr;
You will need #include<string.h>
The memory will need to be free()'d in the delete() function.
free(temp->data);
Do this before freeing temp
char *data
that variable from struct is always assigned with the address of myStr as its a pointer it would only show you the value of myStr
I can create the linked list. But I could not managed to create the stack with it. (Stack cannot be more than 5, and it can be empty as shown in the link). How can I do it? (C language but C++ functions like new int are allowed)
The structure could be something like:
struct linkedStack {
int elements[5];
int top;
struct linkedStack *next;
};
Then manage the stack with top (equals to zero at the beginning)...
Post your code please so we can understand what you are trying to make.
This example can help you
#include<stdio.h>
#include<conio.h>
#include<process.h>
#include<stdlib.h>
#include<alloc.h>
void Push(int, node **);
void Display(node **);
int Pop(node **);
int Sempty(node *);
typedef struct stack {
int data;
struct stack *next;
} node;
void main() {
node *top;
int data, item, choice;
char ans, ch;
clrscr();
top = NULL;
printf("\nStack Using Linked List : nn");
do {
printf("\n\n The main menu");
printf("\n1.Push \n2.Pop \n3.Display \n4.Exit");
printf("\n Enter Your Choice");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("\nEnter the data");
scanf("%d", &data);
Push(data, &top);
break;
case 2:
if (Sempty(top))
printf("\nStack underflow!");
else {
item = Pop(&top);
printf("\nThe popped node is%d", item);
}
break;
case 3:
Display(&top);
break;
case 4:
printf("\nDo You want To Quit?(y/n)");
ch = getche();
if (ch == 'y')
exit(0);
else
break;
}
printf("\nDo you want to continue?");
ans = getche();
getch();
clrscr();
} while (ans == 'Y' || ans == 'y');
getch();
}
void Push(int Item, node **top) {
node *New;
node * get_node(int);
New = get_node(Item);
New->next = *top;
*top = New;
}
node * get_node(int item) {
node * temp;
temp = (node *) malloc(sizeof(node));
if (temp == NULL)
printf("\nMemory Cannot be allocated");
temp->data = item;
temp->next = NULL;
return (temp);
}
int Sempty(node *temp) {
if (temp == NULL)
return 1;
else
return 0;
}
int Pop(node **top) {
int item;
node *temp;
item = (*top)->data;
temp = *top;
*top = (*top)->next;
free(temp);
return (item);
}
void Display(node **head) {
node *temp;
temp = *head;
if (Sempty(temp))
printf("\nThe stack is empty!");
else {
while (temp != NULL) {
printf("%d\n", temp->data);
temp = temp->next;
}
}
getch();
}
Wrote this program in C for linked Lists. I am getting an error in insert when trying to insert at the end of the linked list as a segmentation fault. All other cases are working such as inserting initially,inserting in between 2 elements,etc. Spent a lot of time pondering but couldnt figure out?
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
void insert();
void display();
void search();
void delete();
struct node{
int val;
struct node *next;
}*head;
int num,count=0;
void main()
{
char dec = 'E';
printf("Welcome to the Linked List C Program!\n");
head = NULL;
while(1){
printf("Make a Choice:\n");
printf("I.Insert\nD.Delete\nS.Search\nd.Display\nE.Exit\n");
scanf(" %c",&dec);
switch(dec){
case 'I':
insert();
break;
case 'D':
delete();
break;
case 'S':
search();
break;
case 'd':
display();
break;
case 'E':
exit(0);
break;
default:
printf("Wrong input Try Again!\n");
}
}
}
void insert(){
printf("Enter the number to insert:");
scanf("%d",&num);
struct node *temp;
struct node *newnode;
struct node *prev;
int c =0;
//temp = (struct node *)malloc(sizeof(struct node));
newnode = (struct node *)malloc(sizeof(struct node));
//prev = (struct node *)malloc(sizeof(struct node));
newnode->val = num;
if(head==NULL)
{
head = newnode;
head->next = NULL;
}
else
{
temp = head;
//searching whether linked list is in start or end
while(temp->val<num && temp !=NULL)
{
printf("Index:%d Value:%d Address:%p",c,temp->val,temp);
prev = temp;
temp = temp->next;
c++;
printf("TEST\n");
}
if(c==0)
{
head = newnode;
head->next = temp;
}
else
{
prev->next=newnode;
newnode->next=temp;
}
}
}
void display()
{
struct node *temp;
temp = (struct node *)malloc(sizeof(struct node));
temp = head;
while(temp != NULL)
{
printf("%d",temp->val);
temp = temp->next;
}
if(temp == NULL)
{
printf("Not present!");
}
}
void search()
{
printf("Enter the number tosearch for:\n");
scanf("%d",&num);
struct node *temp;
temp=head;
int c=0;
while(temp!=NULL)
{
if(temp->val==num)
{
printf("Present at position %d",c);
c++;
}
else if(temp == NULL)
{
printf("Not present!");
}
else
c++;
temp =temp->next;
}
}
void delete()
{
struct node *temp;
struct node *prev;
temp = head;
printf("Enter the value to delete:\n");
scanf("%d",&num);
int c=0;
while(temp!=NULL)
{
if(temp->val==num)
{
printf("Present at position %d",c);
printf("Deleting this element");
prev->next=temp->next;
free(temp);
c++;
}
else
c++;
prev = temp;
temp =temp->next;
}
if(temp == NULL)
{
printf("Not present!");
}
}
In your while loop, you're checking one of temp's members before checking that temp is not NULL:
while(temp->val<num && temp !=NULL)
reverse that:
while ((temp != NULL) && (temp->val < num))