9007:单链表按值操作

23 篇文章 0 订阅

 Problem Description

对值递增有序的单链表进行以下操作:若表中存在值为x的结点,则将它从表中删除;否则,就往表中插入一个值为x的结点,并保持表值递增有序的性质不变(假设表中没有值相同的元素)。处理后若为空表则不输出。

 Input

每组数据包括3行,第一行表示单链表的长度n(0<=n<50);第二行表示单链表的所有元素;第三行表示x值。

 Output

输出执行操作后的单链表,元素之间用一个空格分隔。

 Sample Input

5
1 3 5 7 9
3
5
1 3 5 7 9
4

 Sample Output

1 5 7 9
1 3 4 5 7 9
#include<iostream>
#include<stdio.h>
#include<string.h>
using namespace std;

struct node {
    int data;
    node* next;
};

class List {
public:
    node* head;
    List() {
        head=new node;
        head->next=NULL;
    }
    void creat(int n) {
        node* r=head;
        int num;
        for(int i=0; i<n; i++) {
            cin>>num;
            node* s=new node;
            s->data=num;
            r->next=s;
            r=s;
        }
        r->next=NULL;
    }

    int fineIndex(int data) {

        node* p=head;
        int count=0;
        while(p->next&&p->next->data!=data) {
            count++;
            p=p->next;
        }
        return count+1;
    }


    int Delete(int index) {
        node* p=head;
        int i=0;
        int data;
        while(p->next&&i++<index-1) {
            p=p->next;
        }
        if(p->next) {
            data=p->next->data;
            node* temp=p->next;
            p->next=p->next->next;
            delete temp;
        }
        return data;

    }


    void Insert(int data) {
        node* p=head;
        while(p->next&&p->next->data<data) {
            p=p->next;
        }
        node* s=new node;
        s->data=data;
        s->next=p->next;
        p->next=s;

    }





    ~List() {
        //     if(head==NULL||head->next==NULL)return;
        node* p=head->next;
        while(p) {
            node* temp=p;
            p=p->next;
            delete temp;
        }
    }

    void print() {

        if(head->next==NULL||head==NULL) {
            return;
        }
        node* p=head->next;
        while(p->next) {

            cout<<p->data<<" ";
            p=p->next;

        }
        cout<<p->data<<endl;
    }


};


int main() {
     int T;
    while(cin>>T) {
        //while(T--) {

        //   int n;
        //cin>>n;
        List* list=new List;
        list->creat(T);
        int data;
        cin>>data;
        int index=list->fineIndex(data);
        if(index>T) {
            list->Insert(data);
        } else {
            list->Delete(index);
        }
        list->print();
        delete list;
        //  }

    }
    return 0;
}

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

haibianyoushark

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值