【发布时间】:2019-12-16 17:37:58
【问题描述】:
我想通过调用一个对象在列表的前面添加一个节点并打印列表的长度。到目前为止,我一直遇到分段错误。我想要一些足够基本的东西,以便我可以从以下方面构建想法:
#include <iostream>
using namespace std;
class Node {
public:
int data;
Node *next; //creating a pointer to store the address of the next node or null (at the end of a linked list)
int key;
Node(int d){
data = d;
next = NULL;
key = -1;
}
};
class LinkedList {
public:
Node *head;
LinkedList (){
head = NULL;
}
void addNodetoFront(int data){
Node *n = new Node(data);//allocate memory on the heap with address that is returned to n (pointer)
n->next=head;
head=n;
if(n != NULL){
n->key = n->next->key+1;
}
else{
n->key = 1;
}
}
};
int main(){
LinkedList linkedlist;
linkedlist.addNodetoFront(2);
linkedlist.addNodetoFront(3);
linkedlist.addNodetoFront(4);
linkedlist.addNodetoFront(5);
linkedlist.addNodetoFront(26);
linkedlist.addNodetoFront(27);
linkedlist.addNodetoFront(9);
linkedlist.addNodetoFront(45);
linkedlist.addNodetoFront(87);
return 0;
}
期望是9个节点的链表,程序打印9个元素。
【问题讨论】:
-
想想当你添加第一个元素时
addToFront做了什么。
标签: c++ class linked-list