G药–链表–增、删
Time Limit: 1000MS Memory Limit: 65536KB
Problem Description
新年伊始,飞神得到了一个叫做药的链表…(弱已词穷…)
初始时链表只有头指针,对链表存在三种操作。
增加一个元素,向链表中增加一个元素,增加后要保证链表从前到后为单调不降序列。
删除一个元素,从链表中删除一个元素,删除后要保证剩余节点仍为单调不降序列。
按序将链表中的元素全部输出。
Input
多组输入。
对于每组数据,第一行一个整数n(1 <= n <= 1000),代表有n次操作。
接下来的n行,每行描述一次操作,形式如下。
A val。表明此时向链表中添加一个元素val(val不会超出int)。
D rank。表明此时要在链表中删除第rank个元素,若不存在,则忽略此次操作。
Q。按序将链表中的元素全部输出,若链表为空,则忽略此次操作。
Output
对于每次第三种操作,按序将链表中的元素全部输出。
Example Input
6
A 1
A 2
A 5
Q
D 3
Q
Example Output
1 2 5
1 2
Hint
Author
zmx
think:
注意当只有头节点的时候,任何删除,输出操作都不进行。
注意字符起前的空格,吸收回车。
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node * next;
};
struct node * Insert(struct node *head, int n)
{
struct node *p= head;
if(p->next)
{
struct node *q = head->next;
while(q)
{
if(q->data>=n)
{
struct node * r = (struct node *)malloc(sizeof(struct node));
r->data = n;
p->next = r;
r->next = q;
break;
}
else
{
p = p->next;
q = q->next;
}
}
if(!q)
{
struct node * r = (struct node *)malloc(sizeof(struct node));
r->data = n;
r->next = NULL;
p->next = r;
}
}
else
{
struct node *q = (struct node *)malloc(sizeof(struct node));
q->next = NULL;
q->data = n;
head->next = q;
}
return head;
}
struct node * Del(struct node * head, int n)
{
struct node * q = head;
if(head->next)
{
struct node * p = head->next;
while(p)
{
n--;
if(n==0)
break;
p = p->next;
q = q->next;
}
if(p)
{
if(p->next)
{
q->next = p->next;
free(p);
}
else
{
q->next = NULL;
free(p);
}
}
}
return head;
}
void show(struct node * head)
{
struct node * p = head;
if(p->next)
{
p = p->next;
while(p)
{
while(p->next)
{
printf("%d ", p->data);
p = p->next;
}
printf("%d\n", p->data);
p = p->next;
}
}
}
int main()
{
int n,m;
char c;
while(~scanf("%d", &n))
{
struct node * head = (struct node *)malloc(sizeof(struct node));
head->next = NULL;
while(n--)
{
scanf(" %c", &c);
if(c=='A')
{
scanf("%d", &m);
head = Insert(head, m);
}
else if(c=='Q')
{
show(head);
}
else
{
scanf("%d", &m);
head = Del(head, m);
}
}
}
return 0;
}