首页 > 其他 > 详细

自己写了一个链表功能还不完善但是简单的增删改查功能都已经实现了

时间:2014-04-27 13:26:12      阅读:504      评论:0      收藏:0      [点我收藏+]
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct teacher
{
	int data;
	struct Node *next;
}SLIST;
int Creat_SList();
int SList_Print();
int SList_NodeInsert(SLIST *pHead, int x, int y);
int Creat_SList(SLIST **handle)
{
	int data = 0;
	int ret=0;
	SLIST *pHead = NULL, *pCur = NULL,*pM=NULL;
	//先分配内存
	pHead = (SLIST *)malloc(sizeof(SLIST));
	if (pHead == NULL)
	{
		ret = -1;
		printf("func Creat_SList err ret=%d", ret);
		return ret;
	}
	pHead->data = 0;
	pHead->next = NULL;

	printf("\nPlease enter the data of node(-1:quit) ");
	scanf("%d", &data);
	pCur = pHead;
	while (data != -1)
	{
		pM = (SLIST *)malloc(sizeof(SLIST));
		if (pM == NULL)
		{
			//SList_Destory(pHead);
			ret = -2;
			printf("func Creat_SList() err:%d malloc err", ret);
			return ret;
		}
		pM->data = data;
		pM->next = NULL;
		
		pCur ->next= pM;
		pCur = pM;
		printf("\nPlease enter the data of node(-1:quit) ");
		scanf("%d", &data);
	}
	*handle = pHead;
	return ret;
//END:
}
int SList_Print(SLIST *pHead)
{
	int ret = 0;
	SLIST *p = NULL;
	p = pHead->next;
	if (pHead == NULL)
	{
		return -1;
	}
	printf("\nBegin ");
	while (p)
	{
		printf("%d\n", p->data);
		p = p->next;
	}
	printf("End ");
	return ret;
}
//在x的出现位置插入y
int SList_NodeInsert(SLIST *pHead, int x, int y)
{
	int ret = 0;
	SLIST *pPre, *pCur, *pM;
	if (pHead == NULL)
	{
		int ret = -1;
		printf("SList_Insert err");
		return ret;
	}
	pPre = pHead;
	pCur = pHead->next;
	//不断的malloc新节点数据域赋值
	pM = (SLIST *)malloc(sizeof(SLIST));
	pM->data = y;
	pM->next = NULL;

	while (pCur)
	{
		if (pCur->data == x)
		{
			break;
		}
		pPre = pCur;
		pCur = pCur->next;
	}
	
	if (pM == NULL)
	{
		ret = -2;
		printf("SList_Insert err");
		return ret;
	}
	pM->next = pCur;//pPre->next;
	pPre->next = pM;//pPre = pM;  
	return ret;
}


//删除 找到y并将它删除
int SList_NodeDel(SLIST *pHead, int y)
{
	int ret = 0;
	SLIST *pPre, *pCur, *pTemp;
	if (pHead == NULL)
	{
		int ret = -1;
		printf("SList_Insert err");
		return ret;
	}
	pPre = pHead;
	pCur = pHead->next;
	while (pCur)
	{
		if (pCur->data == y)
		{
			break;
		}
		pPre = pCur;
		pCur = pCur->next;
	}
	if (pCur == NULL)
	{
		printf("没有找到节点 y:%d", y);
		return -2;
	}
	pPre->next = pCur->next;//pTemp = pPre->next;
							//pPre = pTemp;
	return ret;
}
void main()
{
	SLIST * pHead=NULL;
	Creat_SList(&pHead);

	SList_NodeInsert(pHead, 20, 200);

	SList_Print(pHead);

	SList_NodeDel( pHead,  20);
	SList_Print(pHead);
	system("pause");
}

自己写了一个链表功能还不完善但是简单的增删改查功能都已经实现了,布布扣,bubuko.com

自己写了一个链表功能还不完善但是简单的增删改查功能都已经实现了

原文:http://blog.csdn.net/han1558249222/article/details/24558811

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!