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 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 LiBeAs的带隙等于0.997eV,计算阴离子的N和P
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 来真人,不要ai!matlab有关常微分方程的问题求解决,
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算