题目描述
输入n个整数,先按照数据输入的顺序建立一个带头结点的单链表,再输入一个数据m,将单链表中的值为m的结点全部删除。分别输出建立的初始单链表和完成删除后的单链表。
 
输入
第一行输入数据个数n;
第二行依次输入n个整数;
第三行输入欲删除数据m。
 
第二行依次输入n个整数;
第三行输入欲删除数据m。
输出
第一行输出原始单链表的长度;
第二行依次输出原始单链表的数据;
第三行输出完成删除后的单链表长度;
第四行依次输出完成删除后的单链表数据。
 
第二行依次输出原始单链表的数据;
第三行输出完成删除后的单链表长度;
第四行依次输出完成删除后的单链表数据。
示例输入
10 56 25 12 33 66 54 7 12 33 12 12
示例输出
10 56 25 12 33 66 54 7 12 33 12 7 56 25 33 66 54 7 33
#include <iostream>
#include<bits/stdc++.h>
using namespace std;
struct node
{int data;node *next;
};
int m;
struct node *create(int n)
{int i;node *tail,*head,*p;head=new node;head->next=NULL;tail=head;for(i=0;i<n;i++){p=new node;scanf("%d",&p->data);tail->next=p;tail=p;}return (head);
};
void print(struct node *p)
{struct node *h=p->next;while(h!=NULL){if(h->next==NULL)printf("%d",h->data);elseprintf("%d ",h->data);h=h->next;}
}
void num(node *head)
{int i=0;node *p=head->next;while(p){i++;p=p->next;}printf("%d\n",i);
}
void del(node *p)
{node *h;h=p;node *q;while(h->next){if(h->next->data==m)//删除指定元素;{q=h->next;h->next=q->next;free(q);}elseh=h->next;}
}
int main()
{int n;scanf("%d",&n);node *p=create(n);scanf("%d",&m);num(p);print(p);printf("\n");del(p);num(p);print(p);return 0;
}