|
查看: 1238|回复: 2
|
"C" Linked List
[复制链接]
|
|
|
小弟正在做以下 assignment。请各位高手多多指教~~~

因为小弟也是新手,费了两个星期才用以下 coding 来 create linked list~~~
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define SIZE 16
/* function prototype */
void GetString(char *word);
int main(void)
{
struct listNode
{
char word[SIZE]; /* array used to hold the words */
struct listNode *next;
}; /* end structure listNode */
struct listNode *first; /* points to the first word */
struct listNode *end; /* points to the last word */
char tempWord[SIZE * 2];
char choice[5];
/* get the first word from the user and start the first */
GetString(tempWord);
/* create node */
first = (struct listNode *)malloc(sizeof(struct listNode));
strcpy(first->word, tempWord);
first->next = NULL;
end = first;
/* read fruit name and store in the linked first */
printf("Do you have more fruit? yes or no: ");
scanf("%s", choice);
while (choice[0] == 'y')
{
GetString(tempWord);
end->next = (struct listNode *)malloc(sizeof(struct listNode));
end = end->next;
strcpy(end->word, tempWord);
end->next = NULL;
printf("Do you have more fruit? yes or no: ");
scanf("%s", choice);
}
/* print out the words as entered by user */
end = first;
printf("\nCreated fruit list is:\n");
printf("%s\n", end->word);
while (end->next != NULL)
{
end = end->next;
printf("%s\n", end->word);
}
printf("\n");
getchar();
getchar();
return 0;
}
void GetString(char *word)
{
printf("Enter a fruit name: ");
scanf("%s", word);
while ( strlen(word) > SIZE-1 )
{
printf("Enter a word with 15 letters maximum: ");
scanf("%s", word);
}
}
For alphabetical order sorting,我打算用修改以下 selection sort,因为 data type 是 string 而不是 integer,有点难度,不知道可行吗?
/* adds node to an ascending order linked list */
void add ( struct node **q, int num )
{
struct node *r, *temp = *q ;
r = malloc ( sizeof ( struct node ) ) ;
r -> data = num ;
/* if list is empty or if new node is to be inserted before the first node */
if ( *q == NULL || ( *q ) -> data > num )
{
*q = r ;
( *q ) -> link = temp ;
}
else
{
/* traverse the entire linked list to search the position to insert the
new node */
while ( temp != NULL )
{
if ( temp -> data <= num && ( temp -> link -> data > num ||
temp -> link == NULL ))
{
r -> link = temp -> link ;
temp -> link = r ;
return ;
}
temp = temp -> link ; /* go to the next node */
}
}
} |
|
|
|
|
|
|
|
|
|
|
发表于 18-11-2008 11:43 PM
|
显示全部楼层
给你一盏路灯。。。
去看看ASCII table, ascending order of alphabet 不是那样难的。。。 |
|
|
|
|
|
|
|
|
|
|
发表于 26-11-2008 06:53 PM
|
显示全部楼层
水哦,帮你顶,非常感谢分享源码和心得
两个礼拜,辛苦了~ |
|
|
|
|
|
|
|
|
| |
本周最热论坛帖子
|