#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct node {
char word[20];
struct node *next;
} Node;
Node* createList();
int searchWord(Node*, char[]);
void deleteList(Node*);
int main(void) {
char str[20];
int index = 0;
Node *pHead;
pHead = createList();
puts("Please input the word to search");
scanf("%s", str);
index = searchWord(pHead, str);
if(index ==0)
printf("The word %s does not exist\n", str);
else
printf("The %dth word is %s \n", index, str);
deleteList(pHead);
return 0;
}
Node* createList(){
char str[20];
Node *pNode1, *pNode2, *head = NULL;
setbuf(stdout, NULL);
puts("Please input the line of words");
scanf("%s", str);
while (strcmp(str, "End")!=0){
pNode2 =(Node*)malloc(sizeof(Node));
strcpy (pNode2 -> word, str);
if (head == NULL)
head = pNode2;
else
pNode1 -> next = pNode2;
pNode1 = pNode2;
scanf("%s", str);
}
pNode1 -> next = NULL;
return head;
}
int searchWord(Node* head, char str[]){
//Code here
}
void deleteList(Node *head){
Node *pNode1, *pNode2;
pNode1 = head;
while (pNode1 != NULL){
pNode2 = pNode1 -> next;
free(pNode1);
pNode1 = pNode2;
}
return;
}
补充如下,供参考:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct node {
char word[20];
struct node* next;
} Node;
Node* createList();
int searchWord(Node*, char[]);
void deleteList(Node*);
int main(void)
{
char str[20];
int index = 0;
Node* pHead;
pHead = createList();
puts("Please input the word to search");
scanf("%s", str);
index = searchWord(pHead, str);
if (index == 0)
printf("The word %s does not exist\n", str);
else
printf("The %dth word is %s \n", index, str);
deleteList(pHead);
return 0;
}
Node* createList() {
char str[20];
Node* pNode1, * pNode2, * head = NULL;
setbuf(stdout, NULL);
puts("Please input the line of words");
scanf("%s", str);
while (strcmp(str, "End") != 0) {
pNode2 = (Node*)malloc(sizeof(Node));
strcpy(pNode2->word, str);
if (head == NULL)
head = pNode2;
else
pNode1->next = pNode2;
pNode1 = pNode2;
scanf("%s", str);
}
pNode1->next = NULL;
return head;
}
int searchWord(Node* head, char str[]) {
//Code here
int index = 0;
Node* pNode1 = head;
while (pNode1)
{
index++;
if (strcmp(pNode1->word, str) == 0)
return index;
pNode1 = pNode1->next;
}
if (pNode1 == NULL)
return 0;
}
void deleteList(Node* head) {
Node* pNode1, * pNode2;
pNode1 = head;
while (pNode1 != NULL) {
pNode2 = pNode1->next;
free(pNode1);
pNode1 = pNode2;
}
return;
}