帶有頭節點的鏈表操作

#include<stdio.h>
#include<stdlib.h>
#define LEN sizeof(student)

typedef struct Student{
	int num;
	float score;
	struct Student *next;
}student;

student *create(student *head) {//動態創建帶有頭結點的鏈表,這裏的head指針變量形參可以不用傳來,因爲head指針變量沒有初始化,是野指針 
	student *temp,*p; 
	head=malloc(LEN);
	p=head;
	head->next=NULL;
	do{
		temp=malloc(LEN);
		scanf("%d%f",&(temp->num),&(temp->score));
		temp->next=NULL;
		if(temp->num==0){
			return head;
		}
		p->next=temp;
		p=temp;
	}while(1);
}

void *del(student *head){//刪除指定位置的節點 
	int position;
	int n=1,i;
	student *p,*p1;
	printf("請輸入要刪除鏈表的位置:");
	scanf("%d",&position);
	if(head->next==NULL){
		printf("鏈表爲空\n");
		return;
	}
	p=head->next;
	p1=head;
	i=position;
	while(i-1&&p->next!=NULL){
		p1=p;
		p=p->next;
		n++;
		i--;
	} 
	if(n==position)
		p1->next=p->next;
	else
		printf("位置輸入有誤\n");
}

void insert(student *head){//在輸入的位置之後插入數據
	int position,n=0,i;
	student *p=head,*temp,*data; 
	data=malloc(LEN);
	printf("請輸入插入的位置(輸入0將插入1位置):");
	scanf("%d",&position);
	printf("請輸入插入數據的信息(學號和成績):");
	scanf("%d%f",&(data->num),&(data->score));
	i=position;
	while(i&&p->next!=NULL){
		p=p->next;
		i--;
		n++;
	}
	if(position!=n)
		puts("輸入位置有誤");
	else{
		temp=p->next;
		p->next=data;
		data->next=temp->next;
	}
}

void print(student *head){ 
	student *p=head;
	if(head==NULL||head->next==NULL){
		printf("鏈表爲空\n");
		return;
	}
	p=p->next;
	while(p!=NULL){
		printf("%-10d%-10.2f\n",p->num,p->score);
		p=p->next;
	}
}
int main(){
	student *head;
	printf("請輸入a鏈表的信息(學號和成績,輸入0 0結束):\n"); 
	head=create(head);
	print(head);
	del(head);
	print(head);
	insert(head);
	print(head);
	return 0;
} 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章