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;
}