SDUT1138数据结构上机测试2-1:单链表操作A

来源:互联网 发布:淘宝引流手机软件 编辑:程序博客网 时间:2024/05/20 16:35

此题坑点在对末尾节点的操作,避免指针越界

#include<bits/stdc++.h>using namespace std;struct node{    int data;    struct node *next;}*head,*tail,*q,*p;int n,key;void built(){    head=(struct node *)malloc(sizeof(struct node));    head->next=NULL;    tail=head;    for(int i=0; i<n; i++)    {        p=(struct node *)malloc(sizeof(struct node));        scanf("%d",&p->data);        tail->next=p;        tail=p;    }    tail->next=NULL;}void print(){    p=head->next;    while(p)    {        printf("%d",p->data);        if(p->next)            printf(" ");        p=p->next;    }}void del(){    p=head;    while(p->next)    {        if(p->next->data==key)        {            if(p->next->next==NULL)            {                p->next=NULL;                n--;                break;            }            p->next=p->next->next;            n--;        }        p=p->next;    }}int main(){    scanf("%d",&n);    built();    scanf("%d",&key);    printf("%d\n",n);    print();    del();    printf("\n%d\n",n);    print();}


0 0