经测试,代码之前都正确,主函数最后指针处如果用3个指针分别指(如注释)能正确运行,如果用一个指针(如代码),则会无限循环输出s3的内容,求大神解……
#include<iostream>
#include<string.h>
#include<fstream>
using namespace std;
class song{
int id;
char*name;
char*actor;
public:
song(int a, char*b, char*c){
id = a;
name = new char[strlen(b) + 1];
actor = new char[strlen(c) + 1];
strcpy_s(name, strlen(b) + 1, b);
strcpy_s(actor, strlen(c) + 1, c);
}
song(){};
void setid(int i){ id = i; }
//char* geta(){ return actor; }
bool operator<(song temp){
if (strcmp(actor, temp.actor) < 0)
return true;
return false;
}
void show(){ cout << id << " "<< name << " (" << actor<<")"<< endl; }
};
struct list{
song ge;
list*next;
};
void insert(list*&head, list* charu){
if (head == NULL){
head = charu;
charu->next = NULL;
return;
}
if (charu->ge < head->ge){
charu->next = head;
head = charu;
return;
}
list*p = head, *q = head;
while (p->ge < charu->ge&&p->next != NULL){
q = p;
p = p->next;
}
if (p->ge < charu->ge){
p->next = charu;
charu->next = NULL;
}
else {
charu->next = p;
q->next = charu;
}
return;
}
int main(){
song s1(1, "aaa", "aa"), s2(2, "ccc", "cc"), s3(3, "bbb", "bb");
list*head = NULL, *p = new list, *q = new list, *r = new list;
p->ge = s1;
insert(head, p);
p->ge = s2; //q->ge=s2;
insert(head, p); //insert(head,q);
p->ge = s3; //r->ge=s3;
insert(head, p); //insert(head,r);
list*temp = head;
int i = 1;
while (temp != NULL){
temp->ge.setid(i++);
temp->ge.show();
temp = temp->next;
}
}