2008年12月26日 星期五

Pointer & Dynamic Data Structure》建立 Linked List (C語言)

寫一個程式來建立Linked List ,這個Linked List 中的node 紀錄姓名、年齡以及分數的資料。在程式中,讀入資料並將它們利用Linked List 串聯起來。寫一個函數create_link() 來進行資料讀入以及Linked List 建立的工作。寫一個函數print_link() 來將Linked List 中的資料全部印出來。另外寫一個函數add_score() 來將每一個人的分數都增加一個數字。最後寫一個main() 函數來呼叫create_link()去讀入資料並建立Linked List,呼叫print_link() 將整個Linked List 的資料印出來,讀入要增加的分數,之後呼叫add_score() 將每個人的分數增加,最後再呼叫一次print_link() 來看看結果。
以下是範例:
請輸入總共有幾筆資料:3
John
20,75
Mary
25,80
Joe
22,85
輸出:
Linked List 的內容:(Joe, 22, 85) => (Mary, 25, 80) => (John, 20, 75)
請輸入加給分:15
Linked List 的內容:(Joe, 22, 100) => (Mary, 25, 95) => (John, 20, 90)

1 則留言:

匿名 提到...

#include < stdio.h >
#include < stdlib.h > /* has the malloc prototype */
#include < string.h > /* has the strcpy prototype */
#define TSIZE 45 /* size of array to hold title */

struct exam {
char name[TSIZE];
int age,score;
struct exam * next; /* points to next struct in list */
};
struct exam * head = NULL;
struct exam * prev, * current;
void create_link(int);
void print_link(struct exam * , int);

int main()
{
int count=0;
int add_score=0;
printf("How many data:");
scanf("%d", &count);
create_link(count);
print_link(head, add_score);
puts("add score:");
scanf("%i", &add_score);
print_link(head, add_score);
return 0;
}
void create_link(int count)
{

char input[TSIZE];

//while (gets(input) != NULL && input[0] != '\0')
while (count != 0 && input[0] != '\0')
{
count--;
current = (struct exam *) malloc(sizeof(struct exam));
if (head == NULL) /* first structure */
head = current;
else /* subsequent structures */
prev->next = current;
current->next = NULL;

while(getchar() != '\n')
continue;
//puts("Enter student name:");
gets(input);
strcpy(current->name, input);
//puts("Enter age & score is:");
scanf("%d,%d", &current->age, &current->score);

//puts("Enter next student name:");
prev = current;
}
//return *head;
//print_link(head);

}
void print_link(struct exam * head, int add_score)
{
if(add_score == 0)
{
struct exam * current;
if (head == NULL)
printf("No data entered. ");
else
printf ("Here is the exam results:\n");
current = head;
while (current != NULL)
{
printf("(%s, %d, %d)", current->name, current->age, current->score);
current = current->next;
if(current != NULL)
printf("=>");
}
printf("\n");
}
else
{
struct exam * current;
if (head == NULL)
printf("No data entered. ");
else
printf ("Here is the exam results:\n");
current = head;
while (current != NULL)
{
printf("(%s, %d, %d)", current->name, current->age, (current->score)+add_score);
current = current->next;
if(current != NULL)
printf("=>");
}
printf("\n");
}

}