寻找关键点
Problem Description
现定义关键点为一条链中处于中间位置的节点,例如 1 3 4中,3就是这个整数链中的关键点。
现在小玉得到了一个整数链,确保链中的各个数都互不相同且数列中数的个数为奇数。
可是,由于小玉的一些特殊要求,她可能会对这个链进行一些特别的操作。
操作 1 :给定两个数a和b,每次删除链中值为a和值为b两个节点。
操作 2 :给定两个数a和b,每次在链中值为1的节点后插入a,在链中值为2的节点后插入b。
由于小玉特殊的要求,她保证链中肯定会有值为1和2的节点,并且这两个节点永远不会被删除。保证在插入操作之后链中始终不会有重复值的节点。
现在请你写出一个程序,帮助小玉找出链中的关键点。
Input
只有一组数据
先输入一个整数n(10<=n<=100000),且保证n一定为奇数
接下来输入n个互不相同的整数num(1<=num<=10000000)
接着下一行输入一个整数m(1<=m<=4000)
代表接下来有m行
每行有3个数aa,bb,cc. 其中第一个数aa表示操作类型,aa为1代表删除链中值为bb和cc的数,
aa为2代表在链中值为1的节点后增加值为bb的节点,在链中值为2的节点后增加值为cc的节点。
(保证删除的节点在链中一定有,保证插入的节点与链中已有节点不会重复)
Output
对于每次操作,输出一个值h,代表操作完成后链中的关键点。
Sample Input
5
1 3 4 5 2
2
1 3 4
2 3 4
Sample Output
5
5
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct node
{
int data;
struct node*next;
};
struct node *newnode()
{
struct node*t;
t=(struct node*)malloc(sizeof(struct node));
t->next=NULL;
return t;
};
struct node*creat(int n)
{
struct node*head,*p,*tail;
int i;
head=newnode();
tail=head;
for(i=0; i<n; i++)
{
p=newnode();
scanf("%d",&p->data);
tail->next=p;
tail=p;
}
return head;
};
int n;
struct node *del(struct node*head,int bb,int cc)
{
struct node*p,*q;
p=head->next;
q=head;
while(p->next!=NULL)
{
if(p->data==bb)
{
q->next=p->next;
free(p);
p=q->next;
n--;
}
else if(p->data==cc)
{
q->next=p->next;
free(p);
p=q->next;
n--;
}
else
{
q=p;
p=p->next;
}
}
if(p->next==NULL)
{
if(p->data==bb)
{
q->next=NULL;
free(p);
n--;
}
else if(p->data==cc)
{
q->next=NULL;
free(p);
n--;
}
}
return head;
}
struct node*insert(struct node*head,int bb,int cc)
{
struct node *p,*q;
p=head->next;
while(p!=NULL)
{
if(p->data==1)
{
q=newnode();
q->data=bb;
q->next=p->next;
p->next=q;
n++;
}
if(p->data==2)
{
q=newnode();
q->data=cc;
q->next=p->next;
p->next=q;
n++;
}
p=p->next;
}
return head;
};
int key(struct node *head)
{
struct node*p;
p=head;
int i=0,m;
m=(n/2)+1;
while(i<m)
{
p=p->next;
i++;
}
return p->data;
}
int main()
{
int m,ke,aa,bb,cc;
struct node*head;
scanf("%d",&n);
head=creat(n);
scanf("%d",&m);
while(m--)
{
scanf("%d%d%d",&aa,&bb,&cc);
if(aa==1)
{
head=del(head,bb,cc);
}
if(aa==2)
{
head=insert(head,bb,cc);
}
ke=key(head);
printf("%d\n",ke);
}
return 0;
}