在以链接列表的形式(
我正在尝试弄清楚如何创建一个函数,该函数在给出时在堆栈顶部添加新节点:
// a structure for a node
struct node {
int key;
node * next;
};
// a structure for a stack
struct stack {
node * top;
node * bottom;
};
// and the function declaration
void push(stack & s, int key)
它应该适用于空堆栈和一个超过1个节点的堆栈。
我非常困难地了解指针的结构如何工作以及如何添加和删除它们,因此任何解释都将不胜感激。谢谢!
void push(stack *s, int key)
{
struct node newNode;
newNode.key = key;
newNode.next = NULL;
if(s->top == NULL)
{
s->top =&newNode;
s->bottom =&newNode;
}
else{
//Assigning new node to top
s->top->next = &newNode;
//pointing top to new node
s->top = &newNode;
}
}
检查一下。