C单向链表

遍历,插入和删除

#define _CRT_SECURE_NO_WARNINGS
#include<stdlib.h>
#include<string.h>
#include<stdio.h>

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

//创建链表
SLIST *SList_Create();
//打印链表
int SList_Print(SLIST *pHead);
//插入节点 在data=x前 插入data=y
int SList_NodeInsert(SLIST *pHead,int x,int y);
//删除节点
int SList_NodeDel(SLIST *pHead, int x);
//销毁链表
int SList_Destory(SLIST *pHead);


SLIST* SList_Create()
{
	SLIST *pHead, *pM, *pCur;
	int data = 0;
	//申请头节点
	pHead = (SLIST*) malloc(sizeof(SLIST));
	if (pHead == NULL)
	{
		return NULL;
	}
	pHead->data = 0;
	pHead->next = NULL;

	pCur = pHead;
	//不断增加新节点 输入-1时不再增加
	while ( data != -1 )
	{
		printf("Input node data(-1 exit): \n");
		scanf("%d",&data);

		//初始化新节点
		pM = (SLIST *)malloc(sizeof(SLIST));
		if (pM == NULL)
		{
			return NULL;
		}

		pM->data = data;
		pM->next = NULL;

		//新节点加入链表尾部
		pCur->next = pM;
		
		//尾部后移
		pCur = pCur->next;

	}
	return pHead;
}


int SList_Print(SLIST *pHead)
{
	SLIST *tmp;
	if (pHead==NULL)
	{
		return -1;
	}

	tmp = pHead->next;
	printf("SLIST: \n");
	while (tmp->next != NULL)
	{
		printf("%d \t",tmp->data);
		tmp = tmp->next;
	}
	printf("\n");
	return 0;
}

int SList_NodeInsert(SLIST *pHead, int x, int y)
{
	SLIST  *pM, *pCur;
	int data = 0;

	pM = (SLIST *)malloc(sizeof(SLIST));
	if (pM == NULL)
	{
		return NULL;
	}
	pM->next = NULL;
	pM->data = y;

	pCur = pHead;

	//找到要插入的节点
	while ( (pCur->next)->data != x)
	{
		pCur = pCur->next;
	}

	//先记录下个节点
	pM->next = pCur->next;
	//修改当前节点的下一节点
	pCur->next = pM;

	return 0;

}

int SList_NodeDel(SLIST *pHead, int x)
{
	SLIST  *pM, *pCur,*tmp;
	int data = 0;

	pCur = pHead;
	while ((pCur->next)->data != x)
	{
		pCur = pCur->next;
	}
	tmp = pCur->next;
	
	pCur->next = (pCur->next)->next;
	
	free(tmp);
}

void main()
{
	SLIST *t1 = SList_Create();
	int p = SList_Print(t1);
	int x, y;
	printf("在x节点前插入y \n");
	scanf("%d",&x);
	scanf("%d",&y);
	p = SList_NodeInsert(t1,x,y);
	p = SList_Print(t1);
	printf("删除节点:\n");
	scanf("%d", &x);
	p = SList_NodeDel(t1,x);
	p = SList_Print(t1);
	system("pause");
	return;

}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值