单向链表

单向链表模版代码:

功能:
1、建立链表(2种)
2、按成绩高低插入某学生成绩
3、删除某个作弊学生的成绩
4、展示所有学生的成绩

#include <iostream>    
using namespace std;

typedef struct student {
    int id;
    float score;
    struct student *next;
}stu, *stull;

void createtail(stull &head,int n){//尾插法
    stull tail;
    head = (struct student *)malloc(sizeof(stu));
    head -> next = NULL;
    tail = head;
    for(int i=0; i<n; i++){
        stull p;
        p = (struct student *)malloc(sizeof(stu));
        cout<<"输入学生ID:"<<endl;
        cin>> p->id;
        cout<<"输入学生成绩:"<<endl;
        cin>> p-> score;
        if(head -> next == NULL){
            head -> next = p;
            p -> next = NULL;
            tail = p;
        }
        else{
            tail -> next = p;
            p -> next = NULL;
            tail = p;    //注意tail的指向问题
        }
    }
}
/*当头指针为空时将头指针指向p,p指向NULL,尾指针指向p
      当头指针不为空时,尾指针指向p,p指向NULL,tail指向p。 */

void createhead(stull &head,int n){//头插法
    stull p;
    head = (struct student *)malloc(sizeof(stu));
    head -> next = NULL;
    for(int i = 0; i<n; i++){
        p=(struct student *)malloc(sizeof(stu));
        cout<<"输入学生ID:"<<endl;
        cin>> p -> id;
        cout<<"输入学生成绩:"<<endl;
        cin>> p -> score;
        if( head->next == NULL){
            head -> next = p;
            p -> next = NULL;
        }
        else{
            p -> next = head -> next;
            head -> next = p;
           // p -> next=NULL;
        }
    }
}
/*当头指针为空,将头指针指向p,p指向NULL
  当头指针不为空时,将p指向首源节点,将头指针指向p*/

void init(stull &head){//插入功能 不是初始化、、、
    stull p;
    p=(struct student *)malloc(sizeof(stu));
    cout<<"插入学生ID:"<<endl;
    cin >> p -> id;
    cout<<"插入学生成绩"<<endl;
    cin >> p -> score;
    stull t;
    t=head;
    for( ;t;t=t->next ){
        if( t -> next->score > p->score && t->score < p->score){
            p -> next = t->next;
            t -> next = p;
            break;
        }
    }
}

void delet(stull &head,int id){ //删除id的节点
    stull t;
    t=head;
    for(; t;t=t -> next){
        if(t -> next -> id==id){
            stull temp;
            temp=t -> next;
            t -> next = temp -> next;
            free(temp);
            break;
        }
    }
}

void display(stull &head){//展示功能
    stull t;
    t=head -> next;
    while(t!=NULL){
        cout<<"ID:"<< t->id <<endl;
        cout << "score:" << t -> score << endl;
        t = t -> next;
    }
}
int main() {
    stull head;
    head=(struct student *)malloc(sizeof(stu));
    int n;
    cout<<"学生数目:"<<endl;
    cin>>n;
    createhead(head,n);
    display(head);
    int k;
    cout<<"输入作弊学生ID:"<<endl;
    cin>>k;
    delet(head,k);
    display(head);
    init(head);
    display(head);

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值