C语言链表的一般操作,创建,插入,遍历,删除

#include "stdlib.h"
#include "stdio.h"
#include "string.h"

typedef struct Node
{
	int data;
	struct Node *next;
}SLIST;

// 尾插法创建链表
SLIST *Creat_SList()
{
	//1 创建头结点并初始化
	SLIST *pHead = NULL;
	SLIST *pCur = NULL;
	SLIST *pM = NULL;
	int data = 0;
	pCur = pHead = (SLIST *)malloc(sizeof(SLIST));
	pHead->data = 0;
	pHead->next = NULL;

	//2循环创建结点,结点数据域中的数值从键盘输入,
	//以-1作为输入结束标志
	printf("\nPlease enter the data of node(-1:quit) ");
	scanf("%d", &data);

	while(data != -1)
	{
		pM = (SLIST*)malloc(sizeof(SLIST));
		pM->data = data;
		pM->next = NULL;

		pCur->next = pM;
		pCur = pM;
		printf("\nPlease enter the data of node(-1:quit) ");
		scanf("%d", &data);
	}
	return pHead;
}


int SList_Print(SLIST *pHead)
{
	SLIST* pCur = NULL;
	if (!pHead)
	{
		return -1;
	}
	pCur = pHead->next;
	while (pCur)
	{
		printf("%d\n", pCur->data);
		pCur = pCur->next;
	}

	return 1;
}
//在结点数值为x的前面插入y
int SList_NodeInsert(SLIST *pHead, int x, int y)
{
	SLIST* pM = NULL;
	SLIST* pCur = NULL;
	SLIST* pLast = NULL;
	if (!pHead)
	{
		return -1;
	}
	pLast = pHead;
	pCur = pHead->next;

	pM = (SLIST*)malloc(sizeof(SLIST));
	pM->data = y;
	pM->next = NULL;

	while (pCur)
	{
		if (pCur->data == x)
		{
			
			break;
		}
		pLast = pCur;
		pCur = pCur->next;
	}

	pM->next = pCur;
	pLast->next = pM;

	return 1;
}


//删除结点为y的链表结点
int SList_NodeDel(SLIST *pHead, int y)
{
	SLIST* pCur = NULL;
	SLIST* pLast = NULL;
	if (!pHead)
	{
		return -1;
	}
	pLast = pHead;
	pCur = pHead->next;
	while (pCur)
	{
		if (pCur->data == y)
		{
			break;
		}
		pLast = pCur;
		pCur = pCur->next;
	}
	if (!pCur)
	{
		return -1;
	}
	pLast->next = pCur->next;
	free(pCur);
	return 1;
}


int SList_Destory(SLIST *pHead)
{
	SLIST* pNext = NULL;
	SLIST* pCur = NULL;

	if (!pHead)
	{
		return -1;
	}

	pCur = pHead;
	pNext = pCur->next;
	
	while (1)
	{
		free(pCur);
		pCur = pNext;
		if (!pCur)
		{
			break;
		}
		pNext = pNext->next;		
	}

	return 1;
}

int main()
{
	SLIST* pHead = Creat_SList();

	if (!pHead)
	{
		return -1;
	}

	SList_Print(pHead);

	SList_NodeInsert(pHead, 20, 19);
	SList_Print(pHead);

	SList_NodeDel(pHead, 19);
	SList_Print(pHead);

	SList_Destory(pHead);

	return 0;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值