1. 程式人生 > >輸入一個年齡,刪除連結串列中所有相同年齡的節點,譚浩強書中錯誤程式碼糾正

輸入一個年齡,刪除連結串列中所有相同年齡的節點,譚浩強書中錯誤程式碼糾正

#include<stdio.h>
#define N 5
struct student{
	int num;
	char name[10];
	int age;
	double score;
	struct student *next;
};
int main(){
	struct student *p1,*p2,*head;
	struct student cla1[N] = {{201,"Tom",18,89.4},{202,"Bob",19,90.4},{203,"Dog",19,98.4},{204,"Cat",20,78.3},{205,"Jarry",18,76.2}};
	int i,del_age;
	head = cla1;
	printf("原列表為:\n");
	for(i = 1,p1 = head;i <= N;i++){
		if(i == N)
			p1->next = NULL;
		else
			p1->next = cla1+i;
		printf("%-4d%-7s%-3d%-5.2f\n",p1->num,p1->name,p1->age,p1->score);
		p1 = p1->next;
	}
	printf("輸入需要刪除的年齡:\n");
	scanf("%d",&del_age);
	p1 = head;
	while(p1 != NULL){
		if(p1->age == del_age){
			if(head == p1)
				head = head->next;
			else
				p2->next = p1->next;
			p1 = p1->next;
		}
		else{
			p2 = p1;
			p1 = p1->next;
		}
	}
	printf("刪除結果為:\n");
	p1 = head;
	while(p1 != NULL){
		printf("%-4d%-7s%-3d%-5.2f\n",p1->num,p1->name,p1->age,p1->score);
		p1 = p1->next;
	}
	return 0;
}