链表生成并删除某一个节点

来源:互联网 发布:ug加工编程实例 编辑:程序博客网 时间:2024/06/07 06:04
<span style="font-size:18px;">//链表生成并删除某一个节点#include<iostream>using namespace std;struct student{    long number;    float score;    student * next;};student * head;   //链首指针student * create(){    student * ps;  //创建的结点指针    student * pEnd;   //链尾指针,用于在后面插入结点    ps = new student;   //新建一个结点,准备插入链表    cin >> ps->number >> ps->score;    //给结点赋值    head = NULL;       //一开始链表为空    pEnd = ps;    while (ps->number != 0)   //<span style="font-size:18px;"> (0时结束)</span>    {        if (head == NULL)            head = ps;        else            pEnd->next = ps;        pEnd = ps;        ps = new student;        cin >> ps->number >> ps->score;    }    pEnd->next = NULL;    delete ps;    return(head);}void showlist(student * head){    cout << "now the iterms of list are \n";    while (head)    {        cout << head->number << "," << head->score << endl;        head = head->next;    }}void Delete(student * head, long number)    //调用的结点删除函数{    student * p;    if (!head)    {        cout << "\nList null!\n";        return;     //表示未作删除    }    if (head->number == number)//该死,怪不得不能删除链表后面指针if (head->number = number)//要删除的节点在链首    {        p = head;        head = head->next;        delete p;        cout << number << "the head of the listr have been deleted \n";        return;    }    for (student * pguard = head; pguard->next; pguard = pguard->next)    {        if (pguard->next->number == number)  //确定下一个节点就是要删除的        {            p = pguard->next;  //待删            pguard->next = p->next;            delete p;            cout << number << "have been deleted \n";            return;        }    }    cout << number << "not found!\n";}void main(){    showlist(create());    Delete(head, 14);}</span>

列如输入:54 3.4

                  23 3.2

                  24 3.5

                  15 4.1

                   66 4.0

                   0 0.0    (0时结束)

得到输出:54 3.4

                  23 3.2

                  24 3.5

                  15 4.1

                   66 4.0

                  14not found!


0 0