1138—单链表操作

输入n个整数,先按照数据输入的顺序建立一个带头结点的单链表,再输入一个数据m,将单链表中的值为m的结点全部删除。分别输出建立的初始单链表和完成删除后的单链表。
Input
第一行输入数据个数n;
第二行依次输入n个整数;
第三行输入欲删除数据m。
Output
第一行输出原始单链表的长度;
第二行依次输出原始单链表的数据;
第三行输出完成删除后的单链表长度;
第四行依次输出完成删除后的单链表数据。
Sample Input

10
56 25 12 33 66 54 7 12 33 12
12

Sample Output

10
56 25 12 33 66 54 7 12 33 12
7
56 25 33 66 54 7 33

#include<iostream>
using namespace std;
//定义类型
struct link
{
    int data;
    struct link* next;
};
//创建链表
struct link* createlist(int n)
{
    struct link* head=new struct link;
    struct link* pre=head;
    for(int i=0;i<n;i++)
    {
        struct link* p=new struct link;
        cin>>p->data;
        pre->next=p;
        pre=p;
        p->next=NULL;
    }
    return head;

};
//输出链表
void display(struct link*head)
{
    struct link* p=head->next;
    while(p!=NULL)
    {
        cout<<p->data;
        if(p->next!=NULL)
        {
            cout<<' ';//输出要注意空格
        }
        p=p->next;
    }
    cout<<endl;
}
//删除元素
int removelist(struct link*head,int x)
{
    struct link* p=head->next;
    int sum=0;
    while(p!=NULL)
    {
        if(p->data==x)
        {
            head->next=p->next;//因为是删除节点,所以让head直接略过P即可
            sum++;
        }
        head=p;//这里的head和上面的pre一样
        p=p->next;
    }
    return sum;
}

int main()
{
    int n,sum,x;
    cin>>n;

    struct link*head=createlist(n);
    cin>>x;

    cout<<n<<endl;

    display(head);

    sum=removelist(head,x);
    cout<<n-sum<<endl;

    display(head);

    return 0;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值