C单向链表

遍历,插入和删除

#define _CRT_SECURE_NO_WARNINGS
#include
#include
#include

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;

}

C单向链表_第1张图片

 

你可能感兴趣的:(C,链表,数据结构)