第十五周项目二----链表类

本文介绍了一个简单的链表类实现,包括插入、追加、连接等基本操作,并演示了如何创建链表、添加元素以及连接两个链表的过程。
/*
* 程序的版权和版本声明部分
* Copyright (c)2013, 烟台大学计算机学院学生
* All rightsreserved.
* 文件名称: 链表类.cpp
* 作 者:赵晓晨
* 完成日期:2013 年06月11日
* 版本号: v1.0
* 对任务及求解方法的描述部分:略
* 输入描述:略
* 问题描述:略
*/
#include<iostream>
using namespace std;

class Student  //定义student类
{
public:
    Student(int n,double s)//定义构造函数
    {
        num=n;
        score=s;
        next=NULL;
    }
    ~Student()//析构函数
    {
        if(!next)
            delete next;
        next=NULL;
    }
    Student *next;   
    int num;
    double score;
};

class MyList  //定义链表类
{
public:
    MyList()
    {
        head=NULL;
    }
    MyList(int n,double s); 
    ~MyList();
    int display();  
    void insert(int n,double s);
    void append(int n,double s); 
    void cat(MyList &il); 
    int length();  
private:
    Student *head;   
};

MyList::MyList(int n,double s)
{
    head=new Student(n,s);
}

MyList::~MyList()
{
    Student *p=head, *q;
    while (p != NULL)
    {
        q = p;
        p = p->next;
        delete q;
    }
    head = NULL;
}

int MyList::display()
{
    if(head==NULL)
    {
        cout<<"empty\n";
        return 0;
    }
    int cnt=0;
    Student *pt=head;
    while(pt)
    {
        ++cnt;
        cout<<pt->num<<", "<<pt->score<<endl;
        pt=pt->next;
    }
    return cnt;
}

void MyList::insert(int n, double s)
{
    Student * pt=new Student(n,s);
    pt->next =head;
    head=pt;
}

void MyList::append(int n,double s)
{
    Student * pt=new Student(n,s);
    if(head==NULL)
        head=pt;
    else
    {
        Student *pts=head;
        Student *pte=pts->next;
        while(pte)
        {
            pts=pte;
            pte=pts->next;
        }
        pts->next=pt;
    }
}

void MyList::cat(MyList& il)
{
    Student *pt=il.head;
    while(pt)
    {
        append(pt->num,pt->score);
        pt=pt->next;
    }
}

int MyList::length()
{
    int cnt=0;
    Student *pt=head;
    while(pt)
    {
        ++cnt;
        pt=pt->next ;
    }
    return cnt;
}

int main()
{
    int n;
    double s;
    MyList head1;
    cout<<"input head1: "<<endl;  
    for(int i=0; i<3; i++)
    {
        cin>>n>>s;
        head1.insert(n,s);  
    }
    cout<<"head1: "<<endl; 
    head1.display();

    MyList head2(1001,98.4);  
    head2.append(1002,73.5);  
    head2.append(1003,92.8);
    head2.append(1004,99.7);
    cout<<"head2: "<<endl;  
    head2.display();

    head2.cat(head1);  
    cout<<"length of head2 after cat: "<<head2.length()<<endl;
    cout<<"head2 after cat: "<<endl;
    head2.display();
    return 0;
}

结果:

体会:

要静下心来一点点的来  夏天浮躁的季节 但是编程时一定要稳下来

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值