加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-15 06:30:53 所属栏目:安全 来源:网络整理
导读:单链表的增删改查实例: #include stdio.h#include stdlib.htypedef struct LinkedList{int elem;LinkedList * next;}List,* PList;PList CreateLinkedList(int size);void DisplayLinkedList(PList L);void InsertLinkedList(PList L,int locate,int elem);

单链表的增删改查实例:

#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("%dt",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);
	}
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读