3583 - 线性链表的查找
输入一个正整数序列,遇负数时停止,建立一个线性链表存储读入的数据,然后从键盘读入一数据x,在该链表中查找有无比x大的数据,有则全部输出,没有则输出‘no found’;
Input
Output
Examples
Input
1 2 3 4 5 -1 3
Output
4 5
Solution C
#include<stdio.h> #include<stdlib.h> typedef struct tagNODE { int number; struct tagNODE* next; }node, * linklist; void InputAndCreate(linklist* L) { linklist p, s; int n; p = *L = (linklist)malloc(sizeof(node)); while (scanf("%d", &n), n >= 0) { s = (linklist)malloc(sizeof(node)); s->number = n; p->next = s, p = s; } p->next = NULL; } void SearchAndOutput(linklist L) { linklist p; int number = 0; int x; p = L->next; scanf("%d", &x); while (p != NULL) { if (p->number > x) { printf("%d ", p->number); number++; } p = p->next; } if (number == 0) { printf("no found"); } } int main() { linklist list; InputAndCreate(&list); SearchAndOutput(list); return 0; }
Solution C++
#include <stdio.h> #include <stdlib.h> struct node { int d; node *next; }; node *create(); // 建立链表 void travel(node *head); // 遍历链表,输出数据 int main() { node *head = create(); travel(head); return 0; } node *create() { node *head = (node *)malloc(sizeof(node)); head->next = NULL; node *rear = head; int a; scanf("%d", &a);; while(a > 0) { node *p = (node *)malloc(sizeof(node)); p->d = a; p->next = NULL; rear->next = p; rear = p; scanf("%d", &a); } return head; } void travel(node *head) { int x; scanf("%d", &x); int flag = 0; for(node *p = head->next; p != NULL; p = p->next) { if(p->d > x) { printf("%d ", p->d); flag = 1; } } if(flag == 0) printf("no found"); }