Queue Implementation using two stacks-Pointers Incompatibility Error - c

The program task is to implement a queue using two stacks.I understand that pointers need to be passed as parameters like this - pop(**&**headA). But when I do that, I get an 'incompatible pointer' compile time error. So, when I execute the code like shown below, I get logical error. It doesn't run the way I want it to.
#include<stdio.h>
typedef struct node{
int data;
struct node *link;
}node;
node *headA = NULL;
node *headB = NULL;
void push(node *,int);
int pop(node *);
void display(node *);
void enQ();
void dQ();
main(){
int choice;
system("cls");
printf("\n\tWelcome to Queue implementation using two stacks.\n");
do{
/* Menu */
printf("\n\tWhat would you like with your queue?\n\n");
printf("1. Insert an element at the front (EnQ)\n2. Delete the last element (DQ)\n3. Exit program\n\nEnter your desired choice with the corresponding serial number :\n\n");
scanf("%d",&choice);
system("cls");
switch(choice){
case 1: enQ();
break;
case 2: dQ();
break;
case 3: printf("\n\tSorry to see you go, hope to see you back soon!\n");
exit(0);
default: printf("\n\tSorry, That option is unavailable. Try again!\n\n");
}
}while (choice >= 0);
}
void enQ(){
int add;
int x,y;
printf("\n\tEnter the item\n");
scanf("%d",&add);
if(headB == NULL){
push(headA, add);
}
else{
while(headB != NULL){
x = pop(headB);
push(headA, x);
}
push(headA, add);
}
while(headA != NULL){
y = pop(headA);
push(headB, y);
}
display(headB);
}
void dQ(){
int del;
int x,y;
if(headB == NULL){
printf("Queue is empty.");
}
else{
while(headB != NULL){
x = pop(headB);
push(headA, x);
}
del = pop(headA);
printf("\n\tThe element deleted is : %d ", del);
while(headA != NULL){
y = pop(headA);
push(headB, y);
}
display(headB);
}
}
void push(node *head, int add){
node *last_node;
last_node = (node*)malloc(sizeof(node));
last_node->data = add;
last_node->link = head;
head = last_node;
}
int pop(node *head){
node *last_node;
int flag = 0;
if(head==NULL)
return flag;
else{
last_node = head;
flag = last_node->data;
head = head->link;
free(last_node);
return flag;
}
}
void display(node *head){
node *my_stack;
if(head == NULL)
printf("\n\tStack is empty\n");
else{
my_stack = head;
printf("\n\tThe elements of the queue are : \n\n\t");
while(my_stack != NULL){
printf("%d\t", my_stack->data);
my_stack = my_stack->link;
}
}
}

int pop(node *head); What is the type of head?
node *headA = NULL; What is the type of headA?
y = pop(&headA); What is the type of &headA?
It should be clear from this that if you want to pass a node ** to pop, you need to declare pop to have a node ** argument: int pop(node **head);
int pop(node **head){
node *last_node;
int flag = 0;
if(*head==NULL)
return flag;
else{
last_node = *head;
flag = last_node->data;
*head = last_node->link;
free(last_node);
return flag;
}
}
You'll want to make this change for push, too, since that changes head, and you want those changes to be visible once push returns: void push(node **head, int add);
void push(node **head, int add){
node *last_node;
last_node = malloc(sizeof *last_node); // don't cast malloc. #include <stdlib.h> and use a C compiler rather than a C++ compiler.
last_node->data = add;
last_node->link = *head;
*head = last_node;
}

Related

Can't traverse through a C linked list

Task is to create a linked list consisting of objects. User inputs data for each individual Node in the main and then the object is being passed to push, which creates the list.
The problem comes in the printList function, where the condition for a break is never met.
For some reason the line head = head->next doesn't do anything, as the address of next with every iteration remains the same.
typedef struct Node {
int a;
char asd[30];
struct Node *next;
}Node;
Node *head = NULL;
void push(Node**head, struct Node* object);
void printList(Node *head);
int main() {
struct Node {
int oA;
char oAsd[30];
struct Node *next;
};
struct Node *object = malloc(sizeof(struct Node));
int c = 0;
while (1) {
printf("This int will be stored in Node %d.\n", ++c);
scanf("%d", &object->oA);
getchar();
if (!object->oA) {
break;
}
printf("This string will be stored in Node %d.\n", c);
gets_s(object->oAsd, 30);
if (!(strcmp(object->oAsd, "\0"))) {
break;
}
push(&head, object);
}
printList(head);
return 0;
}
void push(Node ** head, struct Node* object)
{
Node *tmp = malloc(sizeof(Node));
tmp = object;
tmp->next = (*head);
(*head) = tmp;
}
void printList(Node *head) {
if (head == NULL) {
puts("No list exists.");
exit(9);
}
while (1) {
printf("-------------------------------\n");
printf("|Int: <%d> |||| String: <%s>.|\n", head->a, head->asd);
printf("-------------------------------\n");
if (head->next) {
printf("\n\n%p\n\n", head->next);
head = head->next;
}
else {
break;
}
}
}`
There are two major problems in your code:
You define struct Node both outside main and inside main
Here tmp = object; you copy the value of a pointer to another pointer but you really want to copy the value of a struct to another struct, i.e. *tmp = *object;.
Besides that - don't put head as a global variable.
So the code should be more like:
typedef struct Node {
int a;
char asd[30];
struct Node *next;
}Node;
void push(Node**head, struct Node* object);
void printList(Node *head);
int main() {
Node *head = NULL;
struct Node *object = malloc(sizeof(struct Node));
int c = 0;
while (1) {
printf("This int will be stored in Node %d.\n", ++c);
scanf("%d", &object->a);
getchar();
if (!object->a) {
break;
}
printf("This string will be stored in Node %d.\n", c);
gets_s(object->asd, 30);
if (!(strcmp(object->asd, "\0"))) {
break;
}
push(&head, object);
}
printList(head);
return 0;
}
void push(Node ** head, struct Node* object)
{
Node *tmp = malloc(sizeof(Node));
*tmp = *object; // Copy the struct
tmp->next = (*head);
(*head) = tmp;
}
void printList(Node *head) {
if (head == NULL) {
puts("No list exists.");
exit(9);
}
while (1) {
printf("-------------------------------\n");
printf("|Int: <%d> |||| String: <%s>.|\n", head->a, head->asd);
printf("-------------------------------\n");
if (head->next) {
printf("\n\n%p\n\n", head->next);
head = head->next;
}
else {
break;
}
}
}

Creating struct using pointer

Im working on a program that creates a structure with functions for adding and displaying new nodes. I have a function called "add" and I use it to create new nodes and send them to struct->next but whenever I try to run my function "displayData", the function says that my structure is NULL/empty.
Here is the code.
#include <stdio.h>
#include <stdlib.h>
typedef struct node *nodePtr;
struct node {
int item;
nodePtr next;
};
typedef nodePtr Statistician;
int input();
Statistician newStatistician(); //allocates memory to the structure. Dynamic allocation
void add(Statistician s, int x); //Adds data to the rear
void displayData(Statistician s); //prints entire dataset
int main() {
int operation, data;
Statistician s = NULL;
data = input(); //get new input
add(s,data); //run add function
displayData(s); //run display function
}
int input(){
int x;
printf("Enter data: ");
if (scanf("%d", &x) != 1)
{
printf("\n\nInvalid Input!\n\n");
exit(0);
}
return x;
}
Statistician newStatistician(){
Statistician newStat;
newStat = malloc(sizeof(struct node));
return newStat;
}
void add(Statistician s, int x){
Statistician newNode = newStatistician();
newNode->item = x;
newNode->next = NULL;
if(s == NULL){
s = newNode;
return;
}
while (s != NULL) {
s = s->next;
}
s->next = newNode;
}
void displayData(Statistician s){
Statistician temp = s;
if(s==NULL){
printf("\n\nList is EMPTY.");
printf( "\n\nPress any key.\n" );
getch();
return;
}
printf( "\n\nThe List:\n" );
while (temp != NULL) {
printf(" %d", temp->item);
temp = temp->next;
}
printf( "\n\nPress any key.\n" );
getch();
return;
}
When i use displayData, the output is.
List is EMPTY
You have to pass the head node by reference. Otherwise the functions that change the list will deal with a copy of the head node and the original head node will not be changed.
For example
void add(Statistician *s, int x)
{
Statistician newNode = newStatistician();
newNode->item = x;
newNode->next = NULL;
while ( *s != NULL ) s = &( *s )->next;
*s = newNode;
}
And the function can be called like
add( &s, data );

How can I create this linked list with stack in C?

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();
}

implementing stack with linked list in C

I'm having trouble implementing a Stack using a linked list with struct. The program compiles fine but when I run it, it prints the first element but then reads the next node as a NULL. I think it might be an error with my passing of the stack to the push method but I am not sure and I have not been successful in fixing it so I'm asking for your help:
#include <stdio.h>
#include <stdlib.h>
struct stackNode{
char data;
struct stackNode *nextPtr;
};
typedef struct stackNode StackNode;
typedef StackNode *StackNodePtr;
void convertToPostfix(char infix[], char postfix[]);
int isOperator(char c);
int precedence(char operator1, char operator2);
void push(StackNodePtr *topPtr, char value);
char pop(StackNodePtr *topPtr);
char stackTop(StackNodePtr topPtr);
int isEmpty(StackNodePtr topPtr);
void printStack(StackNodePtr topPtr);
int main(){
convertToPostfix(NULL, NULL);
return 0;
}
void convertToPostfix(char infix[], char postfix[]){
StackNode stack = {'(', NULL};
StackNodePtr stackPtr = &stack;
push(stackPtr, 'a');
//printf("%s\n", stackPtr->data);
printStack(&stack);
}
void push(StackNodePtr *topPtr, char value){
StackNode *node;
node=(StackNodePtr)malloc(sizeof(StackNodePtr));
node->data=value;
node->nextPtr=*topPtr;
*topPtr=node;
}
void printStack(StackNodePtr topPtr){
if(topPtr == NULL){
printf("%s\n", "NOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO");
return;
}
printf("%c\n", topPtr->data);
printStack(topPtr->nextPtr);
}
Any help would be appreciated.
Thanks
Several problems I could see:
1) printStack(&stack); should be printStack(stackPtr); as you are passing address of stackPtr to the push function.
2)
node = (StackNodePtr)malloc(sizeof(StackNodePtr));
should be:
node = malloc(sizeof(StackNode));
3)
push(stackPtr, 'a');
should be:
push(&stackPtr, 'a');
As you need to pass the address of the top pointer.
This is incorrect:
node=(StackNodePtr)malloc(sizeof(StackNodePtr));
as it is only allocating memory for a struct stackNode* (commonly 4-bytes for any pointer type), when it should be allocating memory for a struct stackNode (at least 5 bytes):
node = malloc(sizeof(StackNode));
--
See Do I cast the result of malloc?
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node * link;
};
void push(struct node **, int);
int pop(struct node **);
void display(struct node *);
void printMenu();
int main() {
struct node * p;
p = NULL;
int data, ch, data1;
//char choice[10];
do {
printMenu();
printf("Enter your choice\n");
scanf("%d", &ch);
switch (ch) {
case 1:
printf("Enter the element to be pushed\n");
scanf("%d", &data);
push(&p, data);
break;
case 2:
data1 = pop(&p);
if (data1 != -1000)
printf("The popped element is %d\n", data1);
break;
case 3:
printf("The contents of the stack are");
display(p);
printf("\n");
break;
default:
return 0;
}
} while (1);
return 0;
}
void printMenu() {
printf("Choice 1 : Push\n");
printf("Choice 2 : Pop\n");
printf("Choice 3 : Display\n");
printf("Any other choice : Exit\n");
}
void push(struct node **q, int num) {
struct node *temp;
temp = (struct node *)malloc(sizeof(struct node));
temp->link = (*q);
temp->data = num;
(*q) = temp;
}
void display(struct node *q) {
//Fill in the code here
struct node *temp = q;
if (temp == NULL)
printf(" {}");
while (temp != NULL)
{
printf(" %d", temp->data);
temp = temp->link;
}
}
int pop(struct node **q) {
//Fill in the code here
struct node *temp;
int item;
if (*q == NULL)
{
printf("Stack is empty\n");
return -1000;
}
temp = *q;
item = temp->data;
*q = (*q)->link;
free(temp);
return item;
}

improvement in my linklist program

Here is a program it is working
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node *next, *prev;
};
struct node *root = NULL;
void push(int);
void pop(void);
struct node *create_node(int);
void travel(void);
int main()
{
int i, j, choice, count;
printf("enter choice\n");
scanf("%d", &choice);
count = 0;
while (choice == 1) {
printf("enter a data element");
scanf("%d", &j);
if (count == 0) {
root = (struct node *)malloc(sizeof(struct node));
root->next = NULL;
root->data = j;
} else
push(j);
count++;
printf("enter choice\n");
scanf("%d", &choice);
}
printf("the link list is \n");
//travel function to be created
travel();
}
void push(int data)
{
struct node *t1;
t1 = root;
while (t1->next != NULL) {
t1 = t1->next;
}
t1->next = create_node(data);
}
void pop()
{
}
void travel(void)
{
struct node *t1;
t1 = root;
while (t1->next != NULL) {
printf("%d ", t1->data);
t1 = t1->next;
}
printf("%d ", t1->data);
}
struct node *create_node(int data)
{
struct node *p = (struct node *)malloc(sizeof(struct node));
p->data = data;
p->next = NULL;
p->prev = NULL;
return p;
}
the above program is fully working,I have used a global pointer root.
My problem is if I do not want to use a global pointer root here then how do I maintain
that list because each time I will have to return the root of list in my push pop functions
is there any other way to achieve the same?
The simplest way to achieve this is to pass a pointer to the root node pointer to each of your functions:
void push(struct node **root, int data) { ... }
void pop(struct node **root) { ... }
void travel(struct node *root) { ... }
So, in your main function you might declare a local variable to hold the root pointer:
struct node *root = NULL;
and then when you call push, for example, you pass the address of the root poiner:
push(&root, data);
I strongly recommend that you fix your push and travel functions so that they are robust to the root pointer being NULL. This was discussed in a previous question of yours and you should heed the advice.
If you did that then you could get rid of the test for count being zero and the associated special case code. You would then replace this:
if (count == 0) {
root = (struct node *)malloc(sizeof(struct node));
root->next = NULL;
root->data = j;
} else
push(&root, j);
with this:
push(&root, j);
To drive home the message, your new push would look like this:
void push(struct node **root, int data)
{
if (*root == NULL)
*root = create_node(data);
else
{
struct node *last = *root;
while (last->next != NULL) {
last = last->next;
}
last->next = create_node(data);
}
}
You would need to modify travel also to include a check for the root node being NULL. I will leave that as an exercise for you.
Maintaining both head and tail pointers could be a better approach since it would avoid so many list traversals.

Resources