全功能单向链表

/*
	链表创建
	链表遍历
	节点追加
	节点查找
	节点插入
	节点删除
*/

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

struct Node
{
	int data;
	struct Node * pNext;
};

void create_list(struct Node * pHead)
{
	int len;
	int count = 0;

	pHead->pNext = NULL;

	printf("请输入节点个数:");
	scanf("%d", &len);

	for (int i = 0; i < len; i++)
	{
		struct Node * pNew = (struct Node *)malloc(sizeof(struct Node));

		pHead->pNext = pNew;
		if (i > 20 && i < 60)
		{
			pNew->data = i - (count += 2);
		}
		else if (i >= 60)
		{
			pNew->data = i - 78;
		}
		else
		{
			pNew->data = i;
		}
		pNew->pNext = NULL;
		pHead = pNew;
	}
}

void traverse_list(struct Node * pHead)
{
	while (pHead)
	{
		printf("%d\n", pHead->pNext->data);
		pHead = pHead->pNext;
	}
}

void append_list(struct Node * pHead)
{
	int count;
	int s = 0;
	
	printf("请输入追加节点数:");
	scanf("%d", &count);
	
	while (pHead->pNext)
	{
		pHead = pHead->pNext;
		s++;
	}
	
	for (int i = 0; i < count; i++)
	{
		struct Node * pNew = (struct Node *)malloc(sizeof(struct Node));
		
		pHead->pNext = pNew;
		pNew->data = s++;
		pNew->pNext = NULL;
		pHead = pNew;
	}
}

void insert_list(struct Node * pHead)
{
	int n, num;
	struct Node * pNew = (struct Node *)malloc(sizeof(struct Node));
	struct Node * pTemp = (struct Node *)malloc(sizeof(struct Node));

	printf("请输入你要在第几个节点后面插入:");
	scanf("%d", &n);
	printf("请输入你要插入的数据:");
	scanf("%d", &num);

	for (int i = 0; i < n; i++)
	{
		pHead = pHead->pNext;

		if (!pHead)
		{
			printf("链表目前没那么多节点!!\n");

			return;
		}
	}

	pTemp = pHead->pNext;
	pHead->pNext = pNew;
	pNew->data = num;
	pNew->pNext = pTemp;
}

void delete_list(struct Node * pHead)
{
	int n;
	struct Node * pTemp = (struct Node *)malloc(sizeof(struct Node));

	printf("要删除第几个节点:");
	scanf("%d", &n);

	for (int i = 0; i < n - 1; i++)
	{
		pHead = pHead->pNext;
		
		if (!pHead)
		{
			printf("链表目前没那么多节点!!\n");
			
			return;
		}
	}

	pTemp = pHead->pNext->pNext;
	free(pHead->pNext);
	pHead->pNext = pTemp;
}

void contains(struct Node * pHead)
{
	int d;
	int c = 0;
	int i = 0;

	printf("请输入要查找的数据:");
	scanf("%d", &d);

	while (pHead->pNext)
	{
		i++;

		if (pHead->pNext->data == d)
		{
			c = 1;
			
			printf("第%d个元素的值为%d\n", i, d);
		}

		pHead = pHead->pNext;
	}

	if (0 == c)
	{
		printf("链表中不存在%d!\n", d);
	}
}

int main(void)
{
	struct Node * pHead = (struct Node *)malloc(sizeof(struct Node));
	
	pHead->pNext = NULL;
	create_list(pHead);
	
	//contains(pHead);
	//append_list(pHead);
	//insert_list(pHead);
	//delete_list(pHead);
	//traverse_list(pHead);

	return 0;
}





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值