您的位置:首页 > 编程语言 > C语言/C++

C语言链表的一般操作,创建,插入,遍历,删除

2016-06-22 14:32 501 查看
#include "stdlib.h"
#include "stdio.h"
#include "string.h"

typedef struct Node
{
int data;
struct Node *next;
}SLIST;

// 尾插法创建链表
SLIST *Creat_SList()
{
//1 创建头结点并初始化
SLIST *pHead = NULL;
SLIST *pCur = NULL;
SLIST *pM = NULL;
int data = 0;
pCur = pHead = (SLIST *)malloc(sizeof(SLIST));
pHead->data = 0;
pHead->next = NULL;

//2循环创建结点,结点数据域中的数值从键盘输入,
//以-1作为输入结束标志
printf("\nPlease enter the data of node(-1:quit) ");
scanf("%d", &data);

while(data != -1)
{
pM = (SLIST*)malloc(sizeof(SLIST));
pM->data = data;
pM->next = NULL;

pCur->next = pM;
pCur = pM;
printf("\nPlease enter the data of node(-1:quit) ");
scanf("%d", &data);
}
return pHead;
}

int SList_Print(SLIST *pHead)
{
SLIST* pCur = NULL;
if (!pHead)
{
return -1;
}
pCur = pHead->next;
while (pCur)
{
printf("%d\n", pCur->data);
pCur = pCur->next;
}

return 1;
}
//在结点数值为x的前面插入y
int SList_NodeInsert(SLIST *pHead, int x, int y)
{
SLIST* pM = NULL;
SLIST* pCur = NULL;
SLIST* pLast = NULL;
if (!pHead)
{
return -1;
}
pLast = pHead;
pCur = pHead->next;

pM = (SLIST*)malloc(sizeof(SLIST));
pM->data = y;
pM->next = NULL;

while (pCur)
{
if (pCur->data == x)
{

break;
}
pLast = pCur;
pCur = pCur->next;
}

pM->next = pCur;
pLast->next = pM;

return 1;
}

//删除结点为y的链表结点
int SList_NodeDel(SLIST *pHead, int y)
{
SLIST* pCur = NULL;
SLIST* pLast = NULL;
if (!pHead)
{
return -1;
}
pLast = pHead;
pCur = pHead->next;
while (pCur)
{
if (pCur->data == y)
{
break;
}
pLast = pCur;
pCur = pCur->next;
}
if (!pCur)
{
return -1;
}
pLast->next = pCur->next;
free(pCur);
return 1;
}

int SList_Destory(SLIST *pHead)
{
SLIST* pNext = NULL;
SLIST* pCur = NULL;

if (!pHead)
{
return -1;
}

pCur = pHead;
pNext = pCur->next;

while (1)
{
free(pCur);
pCur = pNext;
if (!pCur)
{
break;
}
pNext = pNext->next;
}

return 1;
}

int main()
{
SLIST* pHead = Creat_SList();

if (!pHead)
{
return -1;
}

SList_Print(pHead);

SList_NodeInsert(pHead, 20, 19);
SList_Print(pHead);

SList_NodeDel(pHead, 19);
SList_Print(pHead);

SList_Destory(pHead);

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: