单向链表-1

单向链表的排序、查找、插入、删除

/***************************************
*           使用单向链表                 *
*   按学生成绩从高到低的顺序存储学生信息     *
*      从中删除不及格学生的信息            *
***************************************/

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
using namespace std;

struct student  /**构建链表的单节点数据元素**/
{
    char name[20];
    float score;
    struct student *next;
};
typedef student NODE ;

NODE *Search(NODE *head,int key)    /**查找关键字小于key的节点的前驱**/
{
    NODE *p;
    p=head;
    while (p->next!=NULL)
    {
        if(p->next->score<key)
            return p;
        p=p->next;
    }
    return p;
}
void InsertNode(NODE *p,NODE *newp)     /**在p之后插入节点newp**/
{
    newp->next=p->next;
    p->next=newp;
}
void DelNode(NODE *p)   /**删除p结点的一个后继结点**/
{
    NODE *q;
    if(p->next!=NULL)
    {
        q=p->next;
        p->next=q->next;
        delete q;
    }
}
void DelList(NODE *head)    /**销毁整个链表**/
{
    NODE *p;
    p=head;
    while(head->next!=NULL)
    {
        head=head->next;
        delete p;
        p=head;
    }
    delete head;
}
void DispList(NODE *head)   /**显示链表各元素**/
{
    NODE *p;
    p=head;
    while (p->next!=NULL)
    {
        cout<<p->next->name<<"\t"<<p->next->score<<endl;
        p=p->next;
    }
}
int main ()
{
    NODE *newp,*head,*p;
    char name[20];
    float score,low=60;
    if((newp=new NODE)==NULL)
    {
        cout<<"no NODE fail!"<<endl;
        exit(0);
    }
    head=newp;
    head->next=NULL;
    cout<<"input name and score(-1 to exit):"<<endl;
    cin>>name>>score;
    while (score>0)
    {
        if((newp=new NODE)==NULL)
        {
            cout<<"no NODE fail!"<<endl;
            exit(0);
        }
        strcpy(newp->name,name);
        newp->score=score;
        newp->next=NULL;
        p=Search(head,score);
        InsertNode(p,newp);
        cin>>name>>score;
    }

    cout<<"Before delete:"<<endl;
    DispList(head);
    for (p=Search(head,low);p->next!=NULL;p=Search(head,low))
        DelNode(p);
    cout<<"after delete:"<<endl;
    DispList(head);
    DelList(head);
    return 0;
}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值