题目:在一个带头结点的单向链表中查找是否有值为 a 的节点,如果有则在该节点前插入值为 key 的节点, 若没有则将 key 节点插入到链表尾.
输入:空
输出:空
#include <stdio.h>
struct node
{
int a;
struct node *next;
};
int main(int argc, const char * argv[])
{
struct node * head, *p, *q;
head = (struct node *)malloc(sizeof(struct node));
head->next = NULL;
int a;
while (scanf("%d", &a) != EOF) {
p=head;
while (p->next != NULL && p->next->a != a) {
p=p->next;
}
q=(struct node *)malloc(sizeof(struct node));
q->next=NULL;
q->a=a;
if (p->next==NULL) {
p->next=q;
}else {
q->next=p->next;
p->next = q;
}
}
return 0;
}