谁能解释这个链接堆栈的c代码?

时间:2018-10-18 17:48:42

标签: c stack

typedef int StackEntryType;

typedef struct node {
        StackEntryType data;
        struct node* Next;
} Node;

typedef struct {
    int no_ele;
    Node *top;
} stack;

void Push(StackEntryType item, stack *S)
{
    Node *np;
    np = (Node*)malloc(sizeof(Node));
    np->data = item;
    np->Next = S->top;
    S->top = np;
    S->no_ele++;
}

我无法理解此Push函数的语句,有人可以帮助我了解这段代码中的情况吗?

2 个答案:

答案 0 :(得分:3)

void Push(StackEntryType item, stack *S)   //  1
{                                          //  2
    Node *np;                              //  3
    np = (Node*)malloc(sizeof(Node));      //  4
    np->data = item;                       //  5
    np->Next = S->top;                     //  6
    S->top = np;                           //  7
    S->no_ele++;                           //  8
}                                          //  9
  1. 开始定义名为Push的函数,该函数以StackEntryType和指向stack的指针作为参数。 stack作为指针传递,因此可以在函数中修改其成员。

  2. 开始于函数Push的主体。

  3. 声明类型为Node的指向np的指针的本地变量。

  4. 通过调用函数sizeof(Node)在免费存储区中分配malloc()字节,并将指向该存储器开头的指针分配给指针npsizeof运算符产生其操作数在内存中占用的字节数。 (Node*)是一种将类型void返回的指针malloc()类型的值转换为Node指针类型的类型转换。此强制转换在C中是不必要的,应避免使用,因为它可以掩盖错误。

  5. 将传递给{{1}的item分配给#4中分配的Push的成员data

  6. 将指向堆栈当前Node的指针分配给#4中分配的top的指针Next

  7. Node指向的新分配的Node设置为np所指向的top中的新stack

  8. 增加S所指向的Stack中存在的节点数。

之前:

S

分配并设置新+-------------------+ | Stack *S | +-------------------+ | int no_ele = 2 | +-------------------------+ | Node *top -------|--> | Node | +-------------------+ +-------------------------+ | StackEntryType data = 2 | +-------------------------+ | struct node *Next ----|--> | Node | +-------------------------+ +-------------------------+ | StackEntryType data = 1 | | struct node *Next = 0 | +-------------------------+ 的成员:

Node

答案 1 :(得分:1)

首先,此代码包含了很多不是C约定的东西。

  • np = (Node*)malloc(sizeof(Node));而非np = malloc(sizeof(Node));
  • StackEntryType而非stack_entry_type

无论哪种方式,让我们跳进去:

    Node *np; // new Node
    np = (Node*)malloc(sizeof(Node)); // allocate memory to for the Node
    np->data = item; // the new Node is the representation of the data item
    np->Next = S->top; 
    S->top = np; // the new element lies on top of the new stack
    S->no_ele++; // this is probably sort of a counter

这是在做什么,它将item放在堆栈顶部,我们链接到从新元素到旧顶部的指向,新元素变为新顶部。 计数器可能在其他地方用于处理具有空堆栈和非空堆栈的不同情况。

如果还有其他问题,请随时提问