Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pushing to a stack containing ONLY unique values in C

I've implemented a stack with pointers, that works like it's suppose too. Now, I need it push to the stack, without it pushing a duplicate. For example, if I push '2' into the stack, pushing another '2' will still result with only one '2' in the stack because it already exists.

Below is how I went about trying to create the new push function. I know that I'm suppose to traverse the stack and check it for the element I'm adding, but I guess I'm doing that wrong? Can anyone help me out?

    typedef struct Node {
        void *content;
        struct Node *next;
    } Node;

    typedef struct Stack {
        Node *head;
        int count; 
    } Stack;

    void push(Stack *stack, void *newElem) {
        Node *newNode = (Node*) malloc(sizeof(Node));
        if (stack->count > 0) {
             int i;
             for (i = 0, newNode = stack->head; i < stack->count; i++, newNode =
                 newNode->next) {
                   if (newNode->content == newElem) return;
             }
        } else {
            newNode->next = stack->head;
            newNode->content = newElem;
            stack->head = newNode;
            stack->count++;
        }
    }
like image 769
tomato Avatar asked Feb 13 '26 00:02

tomato


1 Answers

if (newNode->content == newElem)

You are comparing two pointers. I guess you want to check whether their contents are equal:

#include <string.h>

if (memcmp(newNode->content, newElem, size) == 0)

The value size may be indicated by the caller. In your case, it should be sizeof(int).

Moreover, once you have traversed the stack, you don't add the element to your data structure.

like image 107
md5 Avatar answered Feb 15 '26 14:02

md5



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!