微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

【数据结构】单链表的增删改查

单链表的增删改查实例:

#include <stdio.h>
#include <stdlib.h>

typedef struct LinkedList
{
	int elem;
	LinkedList * next;
}List,* PList;

PList CreateLinkedList(int size);
void displayLinkedList(PList L);
void InsertLinkedList(PList L,int locate,int elem);
void DeleteLinkedList(PList L,int locate);

void main()
{
	int size;
	PList L;

	printf("输入此单链表的大小:");
	scanf("%d",&size);

	L = CreateLinkedList(size); // 新建和显示
	displayLinkedList(L);
	printf("\n在位置5插入元素2后\n");
	InsertLinkedList(L,5,2);  // 插入并显示
	displayLinkedList(L);
	printf("\n删除位置3元素后\n");
	DeleteLinkedList(L,3);     // 删除3并显示
	displayLinkedList(L);
}

PList CreateLinkedList(int size)
{
	PList P,L;
	L = (PList)malloc(sizeof(List));

	L->elem = 0;
	L->next = NULL;

	P = L;

	for (int i = 0; i < size; i++)
	{
		P->next = (PList)malloc(sizeof(List));  // 首先分配空间 然后再赋值
		P = P->next;
		P->elem = rand()%100;
		P->next = NULL;
	}

	return L;
}

void displayLinkedList(PList L)
{
	PList P = L;
	while (P->next != NULL)
	{
		P = P->next;
		printf("%d\t",P->elem);
	}
	printf("\n");
}

void InsertLinkedList(PList L,int elem) // 在 Locate位置上面插入元素 elem
{
	PList P = L;
	PList Q = NULL;

	if (locate != 0)
		locate--;

	while (P->next != NULL && locate != 0)
	{
		locate--;
		P = P->next;
	}

	if (locate != 0)
		printf("\n输入的范围有误\n");
	else
	{
		Q = (PList)malloc(sizeof(List));  // 包含了 在最后插入
		Q->elem = elem;
		Q->next = P->next;
		P->next = Q;
	}
}


void DeleteLinkedList(PList L,int locate)
{
	PList P = L;
	PList Q = NULL;

	if (locate != 0)
		locate--;

	while (P->next != NULL && locate != 0)
	{
		locate--;
		P = P->next;
	}

	if (locate != 0)
		printf("\n输入的范围有误\n");
	else
	{
		Q = P->next;
		P->next = P->next ->next;
		free(Q);
	}
}

原文地址:https://www.jb51.cc/datastructure/383115.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐