c++中建立链表中的问题 为什么head头指针变化了呢?⼀?求大神啊

2024-11-24 19:45:35
推荐回答(2个)
回答1:

#include
using namespace std;
class User {
char *name;
public:
User() { name = NULL; }
User(char *name) {
this->name = new char[strlen(name) + 1];
strcpy(this->name,name);
}
User(const User &user) {
name = new char[strlen(user.name) + 1];
strcpy(name,user.name);
}
User &operator=(User const &user) {
if(&user != this) {
delete []name;
name = new char[strlen(user.name) + 1];
strcpy(name,user.name);
}
return *this;
}
~User() { delete []name; }
void Show()const { cout << name << endl; }
char *getname()const { return name; }
};

class List {
public:
User Data;
List *Next;
public:
List() { Next = NULL; }
List(char szName[]) {
Data = User(szName);
Next = NULL;
}
~List() {}
};

List *InitList() {
List *head = new List;
head->Data = User("头结点");
head->Next = NULL;
return head;
}

void CreateList(List *head,char szname[]) {
List *q = new List;
List *p = head;
q->Data = User(szname);
while(p->Next != NULL) p = p->Next;
p->Next = q;
}

void ShowList(List *head) {
List *p;
for(p = head->Next; p; p = p->Next)
p->Data.Show();
}

int main() {
List *head = InitList();
int i;
char m[100];
for(i = 0;i < 4;i++) {
cout << "name = ";
cin >> m;
CreateList(head,m);
}
ShowList(head);
// FreeList(head);
system("PAUSE");
return 0;
}

回答2:

add_listnode(use)中的use是一个临时变量,你每次add_listnode的时候都把这个临时变量的地址存起来了,这是不对的。