Noder
Noder

Reputation: 323

How to link stacks to other stacks using Linked List in C programming?

I made my own stack using linked list. But I think this is wrong. my push method is linking Stack1 to other stacks. So, I think it is like...

In my main function,

push(stack1, 10);
push(stack1, 20);

[Stack1] -> [nextStack]
[Stack1] -> [nextStack] (new address from first nextStack)

So, It's like... I am repeating to link stack1 to other stacks again and again...

this is my stack using linked list code below.

#include <stdio.h>
#include <stdlib.h>

typedef struct{
    int data;
   struct stack *top;
}stack;

void push(stack *currentStack, int data){

    if (currentStack->top == NULL)
        fprintf(stderr, "Stack is emtpy");

    else{
        stack *nextStack = (stack*)malloc(sizeof(stack));
        currentStack->data = data;
        currentStack->top = nextStack;

        printf("currentStack is %d\n", currentStack->data);
    }
}

int main(){

    stack* stack1;
    stack1 = (stack*)malloc(sizeof(stack));

    push(stack1, 10);
    push(stack1, 20);

    return 1;
}

and this is the result of my code.

currentStack is 10
currentStack is 20

Upvotes: 0

Views: 96

Answers (1)

user7015283
user7015283

Reputation:

#include <stdio.h>
#include <stdlib.h>

struct stack
{
    int data;
    struct stack *top;
}  *head = NULL;


void push(int data)
{
    if (head == NULL)   //that means stack is empty
    {
        head =(struct node *)malloc(1*sizeof(struct node));
        head->top = NULL;
        head->data = data;
    }
    else
    {
        temp =(struct node *)malloc(1*sizeof(struct node));
        temp->top = head;
        temp->data = data;
        head = temp;
    }

}

Your push() function is incomplete. It should consider two cases one when stack is empty and one when it is not.

Also there is no need to pass a pointer-to-stack in push() function because push() function by default pushes the new element on the topmost node and there is only one stack.

Also you have not initialised your stack pointer with NULL. This might give you undefined behaviour during program run.

Upvotes: 1

Related Questions