大神们,帮忙看看这个指向链表的指针。

经测试,代码之前都正确,主函数最后指针处如果用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;
    }
}

2个回答

这里加上
p = new list;
p->ge = s2;
insert(head, p);
下面类似
p = new list;
p->ge = s3;
insert(head, p);

否则你实际上只有一个节点,你插入的指针指向同一个存储。

baidu_35109033
Twoo8 谢谢,懂了,大神好热心,每次都帮我! 还有,大神睡得好晚……
4 年多之前 回复

插入新节点节点得new一个新节点

baidu_35109033
Twoo8 谢谢大神,懂了!以后还请大神们多多照顾!
4 年多之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐