データ構造とアルゴリズム——チェーンノードの追加と削除

7995 ワード

       ,               
         :
#include<stdio.h>
struct node
{
    int num;
    node *next;
};
node *create()
{
    node *p1,*p2,*head;
    head=p2=p1=new node;
    scanf("%d",&p1->num);
    while(p1->num!=0)
    {
        p1=new node;
        scanf("%d",&p1->num);
        p2->next=p1;
        p2=p1;
    }
    p2->next=NULL;
    return head;
}
void disp(node *head)
{
    node *p=head;
    while(p->next!=NULL)
    {
        if(p->num!=0)
        printf("%d ",p->num);
        p=p->next;
    }
    if(p->num!=0)
    printf("%d
"
,p->num); printf("
"
); } node *insert(node *head) { node *p=head;// head node *newnode = new node;// scanf("%d",&newnode->num); newnode->next=NULL;// next , if(p->num>newnode->num)// { printf("
"
); newnode->next=p;// head=newnode;// head } else// { bool flag=false; p=head;// while(p->next!=NULL) { if(p->next->num>newnode->num) { printf("
"
); newnode->next=p->next; p->next=newnode; flag=true; break; } p=p->next; } if(flag==false)// { printf("
"
); p->next=newnode; } } return head; } node *del(node *head) { node *p=head; int nume; scanf("%d",&nume); if(p->num==nume) { printf("
"
); head=p->next; delete p; return head; } else { bool flag=false; while(p->next->next!=NULL) / / next { if(p->next->num==nume) { printf("
"
); flag=true; p->next=p->next->next; break; } p=p->next; } if(flag==false) / / { printf("
"
); p->next=NULL; } } return head; } int main() { node *head=create(); disp(head); node *head2=insert(head); disp(head2); node *head3=del(head); disp(head3); } ,