1009 说反话 (20 分)
将一个英语的句子按照单词的顺序颠倒,我的想法又是用链表?。先将每个单词找到,按照头插法存下来,然后再将链表输出。有点呆,没事,当练习一下链表。
代码如下:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct vocabulary
{
char *str;
struct vocabulary *next;
}vocab;
void insert(vocab **h,char *str,int len);
int main()
{
char str[82] = {0};
char *t;
int i = 0;
int n1;
vocab *h = (vocab *)malloc(sizeof(vocab));
h->next = NULL;
vocab *p;
fgets(str,82,stdin);
n1 = 0;
do
{
if(str[i] == ' ' || str[i] == '\n') //|| i == 79)
{
t = (char*)malloc(sizeof(char) * i - n1);
strncpy(t,str + n1, i - n1);
insert(&h,t,i - n1);
free(t);
n1 = i + 1;
}
}while(str[++i]);
p = h->next;
vocab *pre = h;
while(p)
{
printf("%s",p->str);
if(p->next)
putchar(' ');
pre = pre->next;
p = pre->next;
free(pre);
}
return 0;
}
void insert(vocab **h,char *str,int len)
{
vocab *p = (vocab *)malloc(sizeof(vocab));
p->str = (char*)malloc(sizeof(char) * len);
p->next = NULL;
strcpy(p->str,str);
p->next = (*h)->next;
(*h)->next = p;
}