尾插法实现带头节点的单链表

15 篇文章 0 订阅

#include"iostream"
#include"stdlib.h"
#include"process.h"
#include"time.h"
using namespace std;
typedef struct Stu {
    int id;
    double score;
    Stu *next;
};
struct Teacher {
    int id;
    string name;
    Teacher *next;
};

void createList(Stu *&sl) { //带有头节点的单链表初始化其头节点
    sl=(Stu*)malloc(sizeof(Stu));
    sl->next=NULL;
    cout<<"Success to initiate"<<endl;
}

void addNode(Stu *sl,int idtmp) { //尾插法建立带有头节点的单链表
    Stu *node=(Stu*)malloc(sizeof(Stu));
    double scoretmp=100.0*(double)rand()/RAND_MAX;//随机生成0-100的随机浮点数 
    node->next=NULL;
    node->id=idtmp;
    node->score=scoretmp;
    Stu *p=sl;
    while(p->next!=NULL) {
        p=p->next;
    }
    p->next=node;
}

void selectWholeList(Stu *sl) {//输出单链表的所有节点数据
    Stu *p=sl;
    while(p->next!=NULL) {
        p=p->next;
        cout<<"id:"<<p->id<<" score:"<<p->score<<endl;
    }
}

void updateListId(Stu *sl,int oldid,int newid) {//更新某节点的id值,使用顺序查找链表方式 
    Stu *p=sl;
    while(p->next!=NULL){
        p=p->next;
        if(p->id==oldid){
            cout<<"Have found it!"<<endl<<"old id:"<<p->id<<" score:"<<p->score<<" new id:"<<newid<<endl;
            p->id=newid;
            break;
        }
    }
}

void deleteNode(Stu *sl,int idtmp){//删除节点 
    Stu *f=sl;
    Stu *b=sl->next;
    while(f->next!=NULL){
        if(b->id==idtmp){
            f->next=b->next;
            free(b);
            cout<<"Success to delete "<<idtmp<<endl;
            break;
        }
        f=f->next;
        b=b->next;
    } 
}

int main() {
    srand((int)time(0));//随机数种子 
    Stu *sl;
    createList(sl);
    int idtmp;
    cout<<"Please key-in the id to each student,with -1 to end the inputting:"<<endl;
    cin>>idtmp;
    cout<<"The score will be built later."<<endl;
    while(idtmp!=-1) {
        addNode(sl,idtmp);
        cout<<"Please key-in the id to each student,with -1 to end the inputting:"<<endl;
        cin>>idtmp;
        system("cls");
    }
    selectWholeList(sl);
    int oldid;
    int newid;
    cout<<"Please key-in the old id and new id to update the list:"<<endl;
    cin>>oldid>>newid;
    updateListId(sl,oldid,newid);
    selectWholeList(sl);
    cout<<"Please key-in the id to delete it:"<<endl;
    cin>>idtmp;
    deleteNode(sl,idtmp);
    selectWholeList(sl); 
    return 0;
}

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值