#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
typedef struct Node
{
int data;
struct Node *next;
}SLIST;
SLIST *SList_Create(); //创建链表
int SList_NodeInsert(SLIST *pHead, int x, int y);//插入链表
int SList_NodeDel(SLIST *pHead, int y);//删除链表
int SList_Destroy(SLIST *pHead);//销毁
SLIST *SList_Create()
{
SLIST *pHead, *pCut, *pM;
int data;
//创建头结点并初始化
pHead = NULL;
pCut = NULL;
pM = NULL;
pHead = (SLIST*)malloc(sizeof(SLIST));
if (pHead == NULL)
{
return NULL;
}
pHead->data = 0;
pHead->next = NULL;
printf("\nplease enter your data ");
scanf("%d", &data);
pCut = pHead;
//不断接受输入malloc的新结点
while (data != -1)
{
//1创建业务结点并初始化
pM = (SLIST*)malloc(sizeof(SLIST));
if (pM == NULL)
{
return NULL;
}
pM->data = data;
pM->next = NULL;
//2新结点,入链表
pCut->next = pM;
pCut = pM;
printf("\nplease enter your data ");
scanf("%d", &data);
}
return pHead;
}
int SList_Print(SLIST *pHead)
{
SLIST *tmp = NULL;
if (pHead == NULL)
{
return -1;
}
tmp = pHead->next;
printf("begin...");
while (tmp)
{
printf("%d ",tmp->data);
tmp = tmp->next;
}
return 0;
}
int SList_NodeInsert(SLIST *pHead, int x, int y)
{
SLIST *pCut, *pM,*pPre;
int data;
//创建新的业务节点
pM = (SLIST *)malloc(sizeof(SLIST));
if (pM == NULL)
{
return -1;
}
//初始化
pM->next = NULL;
pM->data = y;
//遍历链表
pPre = pHead;
pCut = pHead->next;
while (pCut)
{
if (pCut->data == x)
{
break;
}
pPre = pCut;
pCut = pCut->next;
}
//新结点,连接后续结点
pM->next = pPre->next;
//让前驱节点,连接新节点
pPre->next = pM;
return 0;
}
int SList_NodeDel(SLIST *pHead, int y)
{
SLIST *pPre, *pCur;
pPre = pHead;
pCur = pHead->next;
while (pCur)
{
if (pCur->data == y)
{
break;
}
pPre = pCur;
pCur = pCur->next;
}
if (pCur == NULL)
{
printf("没有该%d节点!",y);
return -1;
}
pPre->next = pCur->next;
if (pCur !=NULL)
{
free(pCur);
}
return 0;
}
int SList_Destroy(SLIST *pHead)
{
SLIST *tmp = NULL;
if (pHead==NULL)
{
return -1;
}
tmp = pHead;
while (pHead!=NULL)
{
tmp = pHead->next;
free(pHead);
pHead = tmp;
}
return 0;
}
int SList_Reverse(SLIST *pHead)
{
SLIST *p, *q, *t;
if (pHead == NULL || pHead->next == NULL || pHead->next == NULL)
{
return 0;
}
p = pHead->next;
q = pHead->next->next;
//p = pHead;
//q = pHead->next;
//一个节点,一个结点的位置
while (q)
{
t = q->next; //缓冲后面的链表
q->next = p; //逆置
p = q;
q = t;
}
//头结点变尾节点后 置NULL
pHead->next->next = NULL;
pHead->next = p;
return 0;
}
int main()
{
int ret = 0;
SLIST *pHead = NULL;
pHead = SList_Create();
ret = SList_Print(pHead);
ret = SList_NodeInsert(pHead,20,18);
ret = SList_Print(pHead);
SList_NodeDel(pHead,19);
ret = SList_Print(pHead);
SList_Reverse(pHead);
ret = SList_Print(pHead);
SList_Destroy(pHead);
printf("hello...");
system("pause");
return 0;
}