(optional): 試試讓該Linked list反轉,該如何做?
========================================================
拙著,請指教......
// 使用動態記憶體配置與linked list 撰寫程是讓使用者逐一輸入學生姓名,
// 成績,並依成績高低由高至低排好結點串接的順序,並可印出學生成績,
// 以及查詢某位學生成績
#include
#include
typedef struct TagStudent
{
char name[30];
int grade;
struct TagStudent *next;
}Student;
void InsertStudent(char newname[30],int newgrade);
int StudentCount();
void StudentPrint();
void StudentSearch(char search[]);
Student Head,*ptr=&Head,*current,*previous;
int main(int argc, char *argv[])
{
char ch,Newname[10],SearchName[10];
int Newgrade;
puts("學生成績查詢及輸入系統(停止輸入請按q或Q)\n");
while(1) //當按下不是 Ctrl+q 時
{
printf("請輸入學生姓名:");
scanf("%s",Newname);
if(!stricmp(Newname,"q")) break;
printf("請輸入成績:");
scanf("%d",&Newgrade);
InsertStudent(Newname,Newgrade);
}
puts("輸入結束!!");
printf("共有%d個學生\n",StudentCount());
StudentPrint();
printf("\n請輸入欲查詢學生姓名:");
scanf("%s",SearchName);
StudentSearch(SearchName);
system("PAUSE");
return 0;
}
void StudentSearch(char search[])
{
Student *p=ptr->next;
while(p!=NULL)
{
if(!strcmp(search,p->name))
printf("%s 成績:%d\n",p->name,p->grade);
p=p->next;
}
}
void StudentPrint()
{
Student *p = ptr->next;
while(p!=NULL)
{
printf("姓名:%s \t 分數:%d\n",p->name, p->grade);
p = p->next;
}
}
int StudentCount()
{
int count=0;
Student *p = ptr->next;
while(p!=NULL)
{
count++;
p = p->next;
}
return count;
}
void InsertStudent(char newname[],int newgrade)
{
Student *NewNode;
NewNode=(Student*)malloc(sizeof(Student));
if(NewNode == NULL)
puts("malloc Fail!!");
strcpy(NewNode->name ,newname);
NewNode->grade = newgrade;
NewNode->next=NULL;
if(StudentCount()==0)
{
NewNode->next = ptr->next;
ptr->next = NewNode;
}else
{
previous = ptr;
current = ptr->next;
while(current->grade > NewNode->grade)
{
previous = current;
if (current->next != NULL)
current=current->next;
else
goto END;
}
NewNode->next = current;
END:
previous->next = NewNode;
}
}