代码如下:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
struct SLIST
{
int data;
SLIST* next;
};
SLIST* Slist_Create();
int Slist_Print();
int Slist_NodeInsert();
int Slist_NodeDel();
int Slist_Destory();
SLIST* Slist_Create()
{
SLIST* pHead;
SLIST* pCur;
SLIST* pM;
int data;
//
pHead = new SLIST;
if (pHead == NULL)
{
printf("pHead is null error!\n");
return NULL;
}
pHead->data = 0;
pHead->next = NULL;
pCur = pHead;
//
printf("please input data:\n");
scanf_s("%d", &data);
while (data != -1)
{
pM = new SLIST;
if (pM == NULL)
{
printf("pM is null error!\n");
return NULL;
}
pM->data = data;
pM->next = NULL;
//new node into list
pCur->next = pM;
pCur = pM;
printf("please input data:\n");
scanf_s("%d", &data);
}
return pHead;
}
int Slist_Print(SLIST* pHead)
{
int ret = 0;
if (pHead == NULL)
{
ret = -1;
printf("pHead is null error!\n");
return ret;
}
SLIST* tmp;
tmp = pHead->next;
if (tmp == NULL)
{
ret = -2;
printf("no data......\n");
return ret;
}
printf("Begin:\n");
while (tmp)
{
printf("%d\n", tmp->data);
tmp = tmp->next;
}
printf("End.\n");
return ret;
}
int Slist_NodeInsert(SLIST* pHead, int x, int y)
{
int ret = 0;
SLIST* pM;
SLIST* pCur;
SLIST* pPre;
pPre = pHead;
pCur = pHead->next;
if (pCur == NULL)
{
ret = -1;
printf("no data......\n");
return ret;
}
//
pM = new SLIST;
if (pM == NULL)
{
ret = -2;
printf("pM is null error!\n");
return ret;
}
pM->data = y;
pM->next = NULL;
//
while (pCur)
{
if (pCur->data == x)
{
break;
}
pPre = pCur;
pCur = pCur->next;
}
pM->next = pCur;
pPre->next = pM;
return ret;
}
int Slist_NodeDel(SLIST* pHead, int x)
{
int ret = 0;
if (pHead == NULL)
{
ret = -1;
printf("pHead is null error!\n");
return ret;
}
SLIST* pCur;
SLIST* pPre;
pPre = pHead;
pCur = pHead->next;
while (pCur)
{
if (pCur->data == x)
{
break;
}
pPre = pCur;
pCur = pCur->next;
}
//
if (pCur == NULL)
{
ret = -1;
printf("no data......\n");
return ret;
}
pPre->next = pCur->next;
//remember delete resource
if (pCur != NULL)
{
delete pCur;
}
return ret;
}
int Slist_Destory(SLIST* pHead)
{
int ret = 0;
if (pHead == NULL)
{
ret = -1;
printf("pHead is null error!\n");
return ret;
}
SLIST* tmp;
while (pHead)
{
tmp = pHead->next;
delete pHead;
pHead = tmp;
}
return ret;
}
int main()
{
int ret = 0;
SLIST* pHead;
pHead = Slist_Create();
if (pHead == NULL)
{
ret = -1;
printf("func Slist_Create() error!\n");
return ret;
}
ret = Slist_Print(pHead);
//
ret = Slist_NodeInsert(pHead, 30, 25);
ret = Slist_Print(pHead);
//
ret = Slist_NodeDel(pHead, 30);
ret = Slist_Print(pHead);
ret = Slist_Destory(pHead);
system("pause");
return 0;
}