目前要多练练的链表

#include<stdio.h>
#include<string.h>
#include<malloc.h>

struct Student{
	char name[10];
	struct Student *next;
} ;

// 创建链表
struct Student * create()
{
	// head指向第一个元素
	// current指向当前处理的元素
	// next指向新的,下一个元素
	struct Student *head, *current, *next;
	// 存储姓名
	char str[10];
	// 存储判断符号
	char flag;

	printf("请输入学生姓名:\n");
	scanf("%s", str);
	// 排除回车符号的干扰
	getchar();

	// 申请一块动态内存作为第一个元素的存放处
	head = (struct Student *)malloc( sizeof(struct Student) );
	strcpy( head->name, str );

	current = head;

	printf("是否继续输入:(Y/N)");
	scanf("%c", &flag);

	while( flag != 'N' )
	{
		printf("请输入学生姓名\n");
		scanf("%s", str);
		// 排除回车符号的干扰
		getchar();

		// 申请一块动态内存,作为新的元素存放处
		next = (struct Student *)malloc( sizeof(struct Student) );
		strcpy( next->name, str );

		// 上一个元素的指针指向下一个元素
		current->next = next;

		// 当前指针指向下一个元素
		current = next;
		
		printf("是否继续输入:");
		scanf("%c", &flag);
	}

	// 循环结束,当前指针指向最后一个元素,此时将最后一个元素的指针赋值为NULL
	current->next = NULL;

	return head;
}

// 遍历链表
void list(struct Student *p)
{
	while(1)
	{
		printf("%s \n", p->name);

		if( p->next != NULL )
		{
			p = p->next;
		}else
		{
			break;
		}
	}
}

// 插入链表
void insert(struct Student *p)
{
	// insert要插入的元素
	// current当前处理的元素
	struct Student *insert, *current;
	char str[10];
	int position;

	current = p;
	
	printf("\n请输入要插入的学生姓名\n");
	scanf("%s", str);
	getchar();

	insert = (struct Student *)malloc( sizeof(struct Student) );
	strcpy( insert->name, str );

	printf("需要插入的位置为:\n");
	scanf("%d", &position);

	if( position > 0 )
	{
		// 需要插入position - 1的位置

		while(position > 1)
		{
			current = current->next;
			position--;
		}

		// 插入的元素指向当前元素的下一个
		insert->next = current->next;

		// 当前元素的下一个指向插入的元素
		current->next = insert;		

	}else if ( position == 0 )
	{
		// 插入第一个元素的前面;
		p = insert;
		insert->next = current;
	}
	
	printf("插入元素后最新的成员列表为:\n");
	list(p);
}

int main(void) 
{
	struct Student *p;
	p = create();

	printf("\n当前链表元素为:\n");
	list(p);

	// 循环插入
	while(1)
	{
		insert(p);
	}
}

猜你喜欢

转载自blog.csdn.net/KevinAshen/article/details/79949798
今日推荐