【发布时间】:2016-01-15 11:16:03
【问题描述】:
链表是一种线性数据结构,其中每个元素都是一个单独的对象。列表的每个元素(我们将其称为节点)都包含两项 - 数据和对下一个节点的引用。最后一个节点有对 null 的引用。
所以我尝试在 C++ 中创建一个简单的链表(不是双重或循环的),这是我的代码。我用xcode运行它,语法没有问题。我添加了一个带有键 1 和数据“asd”的节点。我试图打印列表的元素,但我看到的是:(lldb)
有什么问题吗?
提前致谢。
#include <iostream>
#include <string>
using namespace std;
class node {
friend class linkedlist;
private:
int key;
string data;
node *next;
public:
node(int k,string d){
this->key=k;
this->data=d;
}
};
class linkedlist{
private:
node *head;
node *last;
public:
linkedlist(){
this->head=NULL;
this->last=NULL;
}
inline bool is_empty() {return head==NULL;}
void print(){
cout<<"\n";
node *current;
for(current=this->head;current!=NULL;current=current->next){
cout<<"("<<current->key<<","<<current->data<<")"<<" ";
}
cout<<"\n";
}
void insert(int k,string d){
node *new_node=new node(k,d);
this->last->next=new_node;
this->last=new_node;
if(this->is_empty()) this->head=new_node;
}
};
int main()
{
linkedlist *list=new linkedlist();
list->insert(1,"asd");
list->print();
return 0;
}
【问题讨论】:
标签: c++ data-structures linked-list singly-linked-list