C++第十四讲:链表结构

静态链表

#include
struct MyStruct
{
    int id;
    float score;
    MyStruct *next;
};
int main()
{
    struct MyStruct a, b, c, *head, *p;
    a.id = 1; a.score = 88;
    b.id = 2; b.score = 76;
    c.id = 3; c.score = 68;
    head = &a;
    a.next = &b;
    b.next = &c;
    c.next = NULL;
    p = head;
    while (p!=NULL)
    {
        printf("%d,%lf
", p->id, p->score);
        p = p->next;
    }
}

动态链表


#include
using namespace std;
struct stu
{
    int id;
    double score;
    stu *next;
};
int n=0;
stu * creat()//创建链表,输入数据返回头结点 
{
    stu *p1,*p2,*head;
    p1=p2=new stu();
    head=NULL;
    cin>>p1->id>>p1->score;
    while(p1->id!=0) 
    {
        n++;
        if(n==1) head=p1;
        else p2->next=p1;
        p2=p1;
        p1=new stu();
        cin>>p1->id>>p1->score;
    }
        p2->next=NULL;
        return head;
}

void print(stu *head)//遍历链表 
{
    stu *p;
    p=head;
    while(p!=NULL)//是while不是if 
    {
        cout<id<<' '<score<next;
    }
}

int main()
{
    stu *p;
    p=creat();
    print(p);
}
发表评论
留言与评论(共有 0 条评论) “”
   
验证码:

相关文章

推荐文章