学习在C++中实现链表堆栈类
Learning to implement a Linked List Stack class in C++
我想使用堆栈实现链表。这是我的班级:
class LinkedListStack
{
public:
LinkedListStack();
void push(int x);
void pop();
int peek();
private:
struct Node
{
int data;
Node *next;
};
Node *head;
Node *tail;
};
到目前为止,我的实现:
LinkedListStack::LinkedListStack()
{
m_headPtr = 0;
m_tailPtr = 0;
}
void LinkedListStack::push(int x)
{
struct Node* newNode = (struct Node*) malloc(sizeof(struct node));
newNode->data = x;
newNode->next = head;
head = newNode;
}
void LinkedListStack::pop()
{
struct Node* newNode = (struct Node*) malloc(sizeof(struct Node));
newNode->data = NULL;
newNode->next = head;
head = newNode;
delete newNode;
}
int LinkedListStack::peek()
{
return head->data;
}
截至目前,推送和窥视似乎正在起作用,但流行不起作用。请帮忙。我想保持所有实现/风格相同,我只想修复错误以使其工作。
我认为你写错了pop方法。您正在插入一个新项目。我希望这有效。
void LinkedListStack::pop()
{
if (head != 0)
{
struct Node* newHead = head->next;
delete head;
head = newHead;
}
}
相关文章:
- 在 C++ 中使用链表进行堆栈
- 实现基于链表的堆栈的基于范围的 for 循环
- 使用带有链表的堆栈数据结构将中缀转换为后缀
- 使用链表在 c++ 中堆栈嵌入
- 使用链表实现堆栈时出错
- 未分配被释放的指针(将堆栈实现为链表时)
- 在C++中使用链表的堆栈实现中,访问结构体headNode成员count和top会导致运行时错误
- 双链表堆栈删除函数不起作用
- 使用链表在堆栈中插入和删除
- 链表堆栈头文件中"<"标记之前的预期初始值设定项
- 使用链表C++堆栈
- 链表堆栈类的复制构造函数:我的正在向后复制
- 尝试创建链表堆栈时出现链接器错误
- 学习在C++中实现链表堆栈类
- 使用指针的C++链表堆栈
- 实现与链表堆栈的交集
- 在链表堆栈上弹出函数
- 使用链表堆栈
- 使用链表堆栈错误
- 链表堆栈复制构造函数