#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <stdarg.h>
typedef struct Node
{
int data;
struct Node *next;
}SLIST;
int SList_Creacte(SLIST **mypHead)
{
SLIST *pHead, *pM, *pCur;
int data;
int ret=0;
//创建头结点 并初始化
pHead = (SLIST *)malloc(sizeof(SLIST));
if (pHead == NULL)
{
goto END;
ret= -1;
}
pHead->data = 0;
pHead->next = NULL;
printf("\n请输入你的数据\n");
scanf("%d", &data);
pCur = pHead;
while (data != -1)
{
//创建业务节点,并初始化,不断接受输入,malloc新节点
pM = (SLIST *)malloc(sizeof(SLIST));
if (pM == NULL)
{
ret= -1;
goto END;
}
pM->data = data;
pM->next = NULL;
//新节点入链表
pCur->next = pM;
pCur = pM;
printf("\n请输入你的数据\n");
scanf("%d", &data);
}
END:
if (ret != 0)
{
SList_Destory(pHead);
}
else
{
*mypHead = pHead;
}
return pHead;
}
int SList_Print(SLIST *pHead)
{
SLIST *tmp = NULL;
if (pHead == NULL)
{
return -1;
}
tmp = pHead->next;
printf("\r\n开始\r\n");
while (tmp)
{
printf("%d\r\n", tmp->data);
tmp = tmp->next;
}
printf("\r\n结束\r\n");
return 0;
}
int SList_NodeInsert(SLIST *pHead,int x,int y)
{
SLIST *pM, *pCur,*pPre;
pM = (SLIST *)malloc(sizeof(SLIST));
//创建新的业务节点pM
if (pM ==NULL)
{
return -1;
}
pM->next = NULL;
pM->data = y;
//链表遍历
pPre = pHead;
pCur = pHead->next;
while (pCur)
{
if (pCur->data == x)
{
break;
}
pPre = pCur;
pCur = pCur->next;
}
//让新节点链接后续节点
pM->next = pPre->next;
//让前驱节点链接新节点
pPre->next = pM;
return 0;
}
int SList_NodeDel(SLIST *pHead,int x)
{
SLIST *pM, *pCur, *pPre;
int data;
pPre = pHead;
pCur = pHead->next;
while (pCur)
{
if (pCur->data==x)
{
break;
}
pPre = pCur;
pCur = pCur->next;
}
//删除操作
if (pCur==NULL)
{
printf("没有找到节点值为:%d的节点",x);
return -1;
}
pPre->next = pCur->next;
if (pCur!=NULL)
{
free(pCur);
}
return 0;
}
int SList_Destory(SLIST *pHead)
{
SLIST *tmp;
if (pHead)
{
return -1;
}
while (pHead!=NULL)
{
tmp = pHead->next;
free(pHead);
pHead = tmp;
}
return 0;
}
//链表逆置:一个节点一个节点的逆置
int Reverse(SLIST *pHead)
{
SLIST *p = NULL;//前驱节点
SLIST *q = NULL;//当前节点
SLIST *t = NULL;//缓存的一个节点
if (pHead==NULL||pHead->next==NULL||pHead->next->next== NULL)
{
return 0;
}
//初始化
p = pHead->next;
q = pHead->next->next;
while (q)
{
t = q->next;
q->next = p;
p = q;
q = t;
}
//头结点变成尾节点
pHead->next->next= NULL;
pHead->next = p;
return 0;
}
void main()
{
int ret = 0;
SLIST *pHead;
//创建链表
pHead = SList_Creacte(&pHead);
ret = SList_Print(pHead);
if (ret!=0)
{
printf("出错\r\n");
}
//插入链表
SList_NodeInsert(pHead, 5, 100);
if (ret != 0)
{
printf("出错\r\n");
}
SList_Print(pHead);
//删除链表
SList_NodeDel(pHead,5);
SList_Print(pHead);
//逆向链表
Reverse(pHead);
SList_Print(pHead);
//释放链表
SList_Destory(pHead);
printf("hello.....\r\n");
system("pause");
}
07-22
07-22
07-22
07-22