您的位置:首页 > 其它

简单的链表建立与输出

2014-11-25 11:32 381 查看
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <string>

using namespace std;

struct student_type
{
    int num;
    float score;
    struct student_type *next;
};

typedef struct student_type Student;

Student* create(void)
{
    Student *head=NULL;
    Student *p1,*p2;
    int n=0;
    p1=p2=(Student*)malloc(sizeof(Student));
    if(p1!=NULL)
    {
        n++;
        cout<<"\n请输入链表数据(输入0学号表示结束数据输入)————\n";
        cout<<"请输入第一个学生的学号 ";
        cin>>p1->num;
        if(p1->num!=0)
        {
            cout<<"请输入第一个学生的分数 ";
            cin>>p1->score;
            head=p1;
        }
        else
        {
            free(p1);
            return head;
        }
    }
    else
        return head;
    ///开辟新节点
    while(1)
    {
        p1=(Student*)malloc(sizeof(Student));
        if(p1!=NULL)
        {
            cout<<"请输入第"<<n+1<<"个学生的学号"<<endl;
            cin>>p1->num;
            if(p1->num!=0)
            {
                n++;
                cout<<"请输入第"<<n<<"个学生的分数\n";
                cin>>p1->score;
                p2->next=p1;
                p2=p1;
            }
            else
            {
                free(p1);
                p2->next=NULL;
                return head;
            }
        }
    }
}

void print(Student* head)
{
    Student *p=head;
    cout<<"\n输出链表数据\n";
    if(head!=NULL)
    do
    {
        cout<<p->num<<" "<<p->score<<endl;
        p=p->next;
    }while(p!=NULL);
    else
        cout<<"此链表为空"<<endl;
}
int main()
{
    Student *head=NULL;
    int k=0;
    while(1)
    {
        cout<<endl;
        cout<<"1————创建链表"<<endl;
        cout<<"2————输出链表"<<endl;
        cout<<"0————退出"<<endl;
        cout<<"请选择\n";
        cin>>k;
        switch(k)
        {
            case 0: exit(0);
            case 1: head=create();
            continue;
            case 2: print(head);
            continue;
        }
    }
    return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: