【发布时间】:2020-03-20 01:02:53
【问题描述】:
在最近的一个项目中,我一直在使用链表重新创建一个堆栈,并一直试图在链表上输出我的方式,但是它拒绝输出除了堆栈头部之外的任何内容。虽然这通常不会让我烦恼,但我使用了一种非常相似的方法来测试我的删除功能,并且它可以正常工作。 对于 this 的上下文,每个节点都包含一个 char 或 int 变量以及一个 next 指针,节点的默认构造函数将其设为 NULL。我有 And 值(一个 int)和 Or 变量(一个 char)的访问器和修改器。
main.cpp
#include "node.h"
#include "lilis.h"
#include <iostream>
using namespace std;
int main()
{
lilis obj;
char a = '%';
char b = '+';
char c = '=';
char d = '-';
obj.addPush(a);
obj.addPush(b);
obj.addPush(c);
obj.addPush(d);
obj.display();
//obj.rePop();
return 0;
}
lilis.h
#ifndef LILIS_H
#define LILIS_H
class lilis
{
private:
node* head;
public:
lilis();
lilis(node* dupe);
lilis(lilis& dup);
void addPush(int a);
void addPush(char b);
void rePop();
void display();
};
#endif
lilis.cpp(最后注释的代码块是我试图开始工作的,我替换了它,所以它不会无限循环)
#include "node.h"
#include "lilis.h"
#include "iostream"
using namespace std;
lilis::lilis()
{
//ctor
}
lilis::lilis(node* dupe)
{
head=dupe;
}
lilis::lilis(lilis& dup)
{
//ctor
head = dup.head;
}
void lilis::addPush(int a)
{
node* after;
node* store = head;
after->setAnd(a);
after->setNext(head);
head=after;
}
void lilis::addPush(char b)
{
node* after;
node* store = head;
after->setOr(b);
after->setNext(head);
head=after;
}
void lilis::rePop()
{
node* storage = head;
cout << head->getOr();
head = head->getNext();
cout << head->getAnd();
delete storage;
}
void lilis::display()
{
node* after = head;
cout << after->getOr();
after = after->getNext();
cout << after->getOr();
/*while (after->getNext()!=NULL){
std::cout << " " <<after->getAnd();
after = after->getNext();
}*/
}
【问题讨论】:
-
你为什么要建立自己的链表?有
std::list和std::forward_list可供使用。另外,为什么要使用链表?这是一个非常低效的数据结构。在大多数情况下,只需使用std::vector。
标签: c++ linked-list