2209: 建立链表(线性表)
时间限制: 1 Sec 内存限制: 128 MB提交: 282 解决: 185
题目描述
(线性表)设键盘输入n个英语单词,输入格式为n, w1, w2, …,wn,其中n表示随后输入英语单词个数,试编一程序,建立一个单向链表,实现:如果单词重复出现,则只在链表上保留一个。
输入
4
now come now please
输出
now come please
样例输入
3
go come keep
样例输出
go come keep
迷失在幽谷中的鸟儿,独自飞翔在这偌大的天地间,却不知自己该飞往何方……
#include <stdio.h> #include <stdlib.h> #include <string.h> struct Node { char word[20]; int times; Node* next; }; Node* GetNode() { Node* p = (Node*)malloc(sizeof(Node)); p->next = 0; p->times = 1; memset(p->word, 0, 20); return p; } void DestroyList(Node* head) { Node* p = head; while (p) { Node* q = p; p = p->next; free(q); } } Node* InsertNode(Node* head, char word[20]) { Node* p = head; while (p) { if ( strcmp(p->word, word)==0 ) { ++p->times; return p; } p = p->next; } return p; } void DisplayList(Node* head) { while(head) { printf("%s ", head->word); head = head->next; } } int main() { int num = 0; scanf("%d", &num); Node* head = GetNode(); Node* work = head; for (int i=0; i<num; i++) { char word[20] = {0}; scanf("%s", word); if ( InsertNode(head, word)==NULL ) { Node* p = GetNode(); strcpy(p->word, word); work->next = p; work = work->next; } } DisplayList(head->next); DestroyList(head); return 0; }