为什么这个代码运行后什么都显示不出来
#include<iostream>using namespace std;
typedef struct LIST1{
int num;
LIST1* next;
LIST1(int x) : num(x), next(NULL){}
}list1;
class Linked{
private:
public:
list1* head;
Linked(){
head = NULL;
}
void creat(int n,list1* head){
// system("pause");
int i=0;
list1* p;
//list1* p1;
//p->num = n;
//cout<<p->num<<endl;
p = head;
// p = new list1(1);
cout<<87<<endl;
for(i=0;i<n;i++){//注意:为尾插法,head无值
p = new list1(i+1);
head->next = p;
p->next = NULL;
head = head->next;
}
//return head;
}
//void delete(list1* h){//删除h结点,但不到下一个
//}
void bianli(list1* h){
int i = 0;
while(h!=NULL){
cout<<h->num<<endl;
h = h->next;
}
}
};
int main(){
int i=0,n=0,m=0;
cin>>n;
cin>>m;
Linked* l1;
list1* p;
l1->creat(n,l1->head);
cout<<"78"<<endl;
l1->bianli(p);
return 0;
}
这段代码没有主函数,所以没有执行任何操作。在C++中,每一个程序都需要一个入口点,也就是主函数main()。请在代码中添加如下主函数:
int main(){
Linked linked;
linked.creat(10, NULL);
return 0;
}
现在运行你的代码会输出一个链表节点的创建。
另外,你的`creat()`函数有一个问题,你传入的头节点指针没有被正确地赋值。解决办法是将`list1* head`的参数去掉,通过`this->head`来访问类的成员属性。所以`creat()`函数应该改成:
void creat(int n){
int i=0;
list1* p = new list1(n);
this->head = p;
cout << "Node created with value " << n << endl;
}
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。 #include <iostream>
using std::cin, std::cout, std::endl;
using std::ostream;
class list_t {
struct node_t {
int num;
node_t *next;
node_t(int x): num(x), next(nullptr) {}
};
node_t *head = nullptr;
static void list_free(node_t *node) {
if(!node) return;
list_free(node->next);
delete node;
}
public:
list_t(size_t size) {
node_t **next = &this->head;
for(size_t i = 0; i < size; ++i) {
*next = new node_t(i + 1);
next = &(*next)->next;
}
}
~list_t() {this->list_free(this->head);}
friend ostream &operator<<(ostream &os, const list_t &list) {
for(node_t *node = list.head; node; node = node->next)
os << node->num << " ";
return os;
}
};
int main() {
int size; cin >> size;
cout << list_t(size) << endl;
return 0;
}
页:
[1]