Twoo8 2016-05-30 16:10 采纳率: 50%
浏览 1266
已采纳

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

经测试,代码之前都正确,主函数最后指针处如果用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条回答 默认 最新

  • threenewbee 2016-05-30 18:25
    关注

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

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog