动态链表联系总结

来源:互联网 发布:cms系统下载 编辑:程序博客网 时间:2024/06/09 14:40

 以下是解题《C++程序设计题解与上机指导》chapter 7.10的总结

 

#include<iostream>
using namespace std;
#define NULL 0
struct student
{    long num;
    float score;
    student *next;
};
int n=0;

student *create(void);
void print(student *);
student *del(student *,long);
student *insert(student *, student *);


void main()
{    student *head/*, stu */;
    long del_num;
    cout<<"input records:"<<endl;
    head = create();
    print(head);
    do
    {
        cout<<endl<<"input the deleted number:";
        cin>>del_num;
        head=del(head, del_num);
        print(head);
    }while(del_num != 0);
}

student *create(void)
{    student *head=NULL;
    student *p1, *p2;

    p1=new student;
    cin>>p1->num>>p1->score;

    while(p1->num != 0)
    {    n++;
        if(!head)
            head=p1;
        else
            p2->next=p1;
        p2=p1;
        p1 = new student;
        cin>>p1->num>>p1->score;
    }

    p2->next=NULL; //next是指针,不是数值
    return head;
}

void print(student * head)
{    student *p=head;
    cout<<"Now, These "<<n<<" records are: "<<endl;
    while(p != NULL)
    {    cout<<"Num:"<<p->num<<" ";
        cout<<"Score:"<<p->score<<endl;
        p=p->next;
    }
}

student *del(student * head,long num)
{    student *p1, *p2;
    if(NULL == head)
    {    cout<<"List is null!"<<endl; //适当输出相应提示信息
        return head;
    }
       
    p1=head;

    while((p1->num != num) && (NULL != p1->next))
/*不能用“while((p1->num != num) && (NULL != p1))”代替上面的语句
当找不到的时候,while 会因为 p1 == NULL 结束,
然后下面紧接着的语句是 if(p1->num == num),在此句中,
因为 p1 是 NULL,所以 p1->num 是非法访问。 所以使用一个指针的成员务必保证它不是空的
    */
    {    p2=p1;
        p1=p1->next;
    }

    if(p1->num == num)
    {    if(head == p1)
            head=p1->next;
        else
            p2->next=p1->next;
        n--;
        cout<<num<<" has been deleted!";
    }
    else
        cout<<num<<" has not found!";
    cout<<endl;
    return head;
}

/*
student *del(student * head,long num)
{    student *p1, *p2;
    if(head == NULL)
        return head;
    p1=p2=head;
    if(p1->num == num)
    {//注意欲返回的值是head不是p2,由于动态链表的每个节点是无名的,头指针相当于一条链表的入口   
        //p2=p1->next;
        head=p1->next;
        n--;
        return head;
    }

    p1=p1->next;
    while(p1 != NULL)
    {    if(p1->num == num)
        {    p2->next = p1->next;
            n--;
            return head;
        }
        p2=p1;
        p1=p1->next;
    }

    return head;
}
*/



原创粉丝点击