C语言链表梳理-3

#include 

struct Person {
	char * Name;
	int    Age;
	struct Person * Next;
};

struct List {
	char * Name;
	struct Person * Next;
};

void InitList(struct List * pList, char * Name)
{
	pList->Name = Name;
	pList->Next = NULL;
}

void AddItemToList(struct List * pList, struct Person * NewPerson)
{
	struct Person * Last;
	
	/* 如果是空链表 */
	if (pList->Next == NULL)
	{
		pList->Next = NewPerson;
		NewPerson->Next =NULL;
		return;
	}
	/* 如果不是空链表 */
	Last = pList->Next;
	while (Last->Next)
	{
		Last = Last->Next;
	}
	
	/* Last->Next == NULL */
	Last->Next = NewPerson;
	NewPerson->Next = NULL;
}

void PrintList(struct List * pList)
{
	int i = 0;
	
	struct Person *P = pList->Next;
	
	while (P != NULL)
	{
		printf("Person %d: %s is %d\r\n", i++, P->Name, P->Age);
		
		/* 后面还有人, 移动到下一个 */
		P = P->Next;
	}
}

int main(void)
{
	struct List A_List;
	int i = 0;

	struct Person P[] = {
		{"P1", 10, NULL},
		{"P2", 11, NULL},
		{"P3", 12, NULL},
		{"P4", 13, NULL},
		{"P5", 14, NULL},
		{"P6", 15, NULL},
		{"P7", 16, NULL},
		{"P8", 17, NULL},
		{NULL,  0, NULL}, /* 依次判定是否是最后一个元素 */
	};

	InitList(&A_List, "A_class");
	
	while (P[i].Name != NULL)
	{
		AddItemToList(&A_List, &P[i]);
		i++;
	}
	
	PrintList(&A_List);
	
	return 0;
}

C语言链表梳理-3_第1张图片

你可能感兴趣的:(C,c语言,链表,开发语言)