简体   繁体   English

在 C 中使用 typedef 和指针来实现堆栈

[英]Using typedef and pointer in C for implementing a Stack

I am facing problems compiling this code, because I do not know how to work with typedef (but we have to).我在编译这段代码时遇到了问题,因为我不知道如何使用 typedef(但我们必须这样做)。 My method push has item *elem as input but top -> info = *elem does not work.我的方法 push 有 item *elem 作为输入,但 top -> info = *elem 不起作用。 Here is my code:这是我的代码:

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



struct node  
{
int info;

struct node *ptr;
}*top,*top1,*temp;


typedef struct item {

} item;

// my methods
void push(item *elem);
void *pop();
void empty();
void create();

int count = 0;

void create()
{
   top = NULL;
 }


 // pushing the elements in the stack
 void push(item *elem)
 {
    if (top == NULL)
    {
        top =(struct node *)malloc(1*sizeof(struct node));
        top->ptr = NULL;
        top->info = *elem;
    }
   else
    {
        temp =(struct node *)malloc(1*sizeof(struct node));
        temp->ptr = top;
        temp->info = *elem;  // here is the error "not compatible"
        top = temp;
    }
    count++;
 }
    // I also got this, this is for creating a new elem, but I do not  
     // know how to implement this method
  item* new_item(int value) {

 }

First, the typedef:首先是typedef:

struct node  
{
    int info;
    struct node *ptr;
};
typedef struct node item;

And create a pointer:并创建一个指针:

item *top = NULL;

push should simply insert the element at the top of the stack. push应该简单地将元素插入堆栈的顶部。

void push(item *elem)
{
    // I assume elem is already created.
    if (top == NULL)
    {
        top = elem;
    }
    else
    {
        top->ptr = elem;
        top = elem;
    }
    count++;
}

new_item should allocate memory and initialize new_item应该分配内存并初始化

item* new_item(int value)
{
    item *temp = malloc(sizeof(item));
    item->info = value;
    item->ptr = NULL;
}

Somewhere else, create and add....在其他地方,创建和添加....

item *someNewItem = new_item(100);
push(someNewItem);
// Later on, someNewItem needs to be free()'d

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM