Twoo8 2016-05-30 08:48 采纳率: 50%
浏览 1003
已采纳

各路大神帮忙,这个链表怎么不输出呢?

我觉得链表没问题,是不是指针有什么问题……

 #include<iostream>
#include<string.h>
using namespace std;
class song{
    int id;
    char* name;
public:
    char* get(){return name;}
    song(){};
    song(int a,char* b){
        id=a;
        name=new char[strlen(b)+1];
        strcpy_s(name,5,b);
    }
};
struct list{
    song ge;
    list* next;
};
void insert(list*head,list*charu){
    if(head==NULL)
    {
        head=charu;
        charu->next=NULL;
        return ;
    }
    if(strcmp(head->ge.get(),charu->ge.get())>=0)
    {
        charu->next=head;
        head=charu;
        return;
    }
    list*p,*q;
    p=q=head;
    while(p->next!=NULL&&strcmp(p->ge.get(),charu->ge.get())<0)
    {
        q=p;
        p=p->next;
    }

    if(p->next==NULL)
    {
        if(strcmp(p->ge.get(),charu->ge.get())<0)
        {
            charu->next=NULL;
            p->next=charu;
            return;
        }
        else {
            charu->next=p;
            q->next=charu;
            return;
        }
    }
    else {
        charu->next=p;
        q->next=charu;
        return;
    }
}
int main(){
    song aa(5,"aaa"),bb(10,"bbbb"),cc(2,"aabb");
    list *head=NULL,*p=new list;
    p->ge=aa;
    insert(head,p);
    p->ge=bb;
    p->next=NULL;
    insert(head,p);
    p->ge=cc;
    insert(head,p);
    while(head!=NULL)
    {
        cout<<head->ge.get()<<" ";
        head=head->next;
    }
    return 0;
}

  • 写回答

2条回答 默认 最新

  • threenewbee 2016-05-30 09:50
    关注

    void insert(list*head,list*charu)
    这里修改head指针不会反应到形参上

    修改为void insert(list*& head,list*charu)

    但是你的代码看上去还有别的问题

    charu->next=head;
    head=charu;
    这样你的链表岂不是循环了。

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

报告相同问题?

悬赏问题

  • ¥30 matlab解优化问题代码
  • ¥15 写论文,需要数据支撑
  • ¥15 identifier of an instance of 类 was altered from xx to xx错误
  • ¥100 反编译微信小游戏求指导
  • ¥15 docker模式webrtc-streamer 无法播放公网rtsp
  • ¥15 学不会递归,理解不了汉诺塔参数变化
  • ¥15 基于图神经网络的COVID-19药物筛选研究
  • ¥30 软件自定义无线电该怎样使用
  • ¥15 R语言mediation包做中介分析,直接效应和间接效应都很小,为什么?
  • ¥15 Jenkins+k8s部署slave节点offline