C语言创建单向链表实例

//新手学习数据结构,有误之处请多包涵
#include <stdlib.h>
#include <stdio.h>

typedef struct Score{
	float score;
	struct Score *next;
}scoreNode;

//初始化一个表头 
scoreNode* init_scoreNode(void) 
{
	scoreNode* head = (scoreNode*)malloc(sizeof(scoreNode));
	head->score = 0.0;
	head->next = NULL;
	return head;
}

//在位置pos之后插入一个元素 
int insert_score(scoreNode* scoreList,int pos,float score)
{
	scoreNode* newNode = (scoreNode*)malloc(sizeof(scoreNode));
	
	if(newNode == NULL | scoreList == NULL | pos<1)
		return -1;
		
	for(int i = 1;i<pos;i++)
		scoreList = scoreList->next;
		
	newNode->next = scoreList->next;
	newNode->score = score; 
	scoreList->next = newNode;
	
	return 0;
}

//创建一个有n个元素的新列表 
void createScoreList(scoreNode* list,int n)
{
	scoreNode* p = NULL;
	
	for(int i = 0;i<n;i++)
	{
		p = (scoreNode*)malloc(sizeof(scoreNode));
		p->score = 10-i;
		p->next = list->next;
		list->next = p;
	}
}

//删除pos位置的元素 
int delete_score(scoreNode* scoreList,int pos)
{
	scoreNode* p = NULL;
	if(scoreList == NULL | pos<1) return -1;
	for(int i = 1; i<pos; i++)
		scoreList = scoreList->next;
	p = scoreList->next;
	scoreList->next = p->next;
	delete(p);
}

//显示某个链表中的所有元素 
int displayList(scoreNode* list)
{
	if(list == NULL)
		return -1;
	
	int count = 0;
	
	while(list->next != NULL)
	{
		count++;
		list = list->next;
		printf("pos = %d,score = %.2f\n",count,list->score); 
	}
	printf("------------------------------\n");
	return 1;
}

//合并list1和list2到list3,若1和2为有序数组,则合并出来的3也是有序数组 
void mergeList(scoreNode* list1,scoreNode* list2,scoreNode* list3)
{
	list1 = list1->next;
	list2 = list2->next;
	
	while(list1!=NULL && list2!=NULL)
	{
		if(list1->score <= list2->score)
		{
			list3->next = list1;
			list3 = list3->next;
			list1 = list1->next;
		}
		else
		{
			list3->next = list2;
			list3 = list3->next;
			list2 = list2->next;
		}
	}
	list3->next = list1?list1:list2;
	printf("Union Finished\n");
} 

int main()
{
	scoreNode* list1 = init_scoreNode();
	scoreNode* list2 = init_scoreNode();
	scoreNode* list3 = init_scoreNode();
		
	insert_score(list1,1,11.1);
	insert_score(list1,2,22.2);
	insert_score(list1,3,33.3);
	insert_score(list1,4,44.4);
	
	displayList(list1);
	delete_score(list1,3);
	displayList(list1);
	createScoreList(list2,10);
	displayList(list2);
	
	mergeList(list1,list2,list3);
	displayList(list3);
	return 0;
}

 

posted @ 2019-08-13 16:04  昨夜昙花  阅读(11)  评论(0)    收藏  举报