typedef :起別名,可以方便修改數據型別
#include<stdio.h>
typedef struct node
{
int num;
struct node *pNext;
}Node_t,*pNode_t;
typedef struct {
Node_t num;//數據
pNode_t phead = NULL;//指針
}
一、不帶頭結點的鏈表的頭尾插法
void headInsert(pNode_t *ppHead, pNode_t *ppTail, int num)
{
pNode_t pNew = (pNode_t)calloc(1, sizeof(Node_t));
pNew->num = num;
if (*ppHead== NULL)
{
*ppHead = pNew;
*ppTail = pNew;
}
else
{
pNew->pNext = *ppHead;
*ppHead = pNew;
}
}
void tailInsert(pNode_t *ppHead, pNode_t *ppTail, int num)
{
pNode_t pNew = (pNode_t)calloc(1, sizeof(Node_t));
pNew->num = num;
if (*ppHead == NULL)
{
*ppHead = pNew;
*ppTail = pNew;
}
else
{
(*ppTail)->pNext = pNew;
*ppTail = pNew;
}
}
二、不帶頭節點鏈表的有序插入
void sortInsert(pNode_t *ppHead, pNode_t *ppTail, int num)
{
pNode_t pNew = (pNode_t)calloc(1, sizeof(Node_t));
pNew->num = num;
if (*ppHead==NULL)
{
*ppHead = pNew;
*ppTail = pNew;
}
else if (pNew->num < (*ppHead)->num)
{
pNew->pNext = *ppHead;
*ppHead = pNew;
}
else
{
pNode_t pPre = *ppHead;
pNode_t pCur = pPre->pNext;
while (pCur)
{
//if (pNew->num<pCur->num&&pNew->num>pPre->num)
if (num < pCur->num) //因爲鏈表有序且指針遍歷,所以只要找到num大於pCur對應值的節點就行。
{
pNew->pNext = pCur;
pPre->pNext = pNew;
break;
}
pPre = pCur;
pCur = pCur->pNext;
}
if (pCur == NULL)
{
(*ppTail)->pNext = pNew;
*ppTail = pNew;
}
}
}
三、不帶頭結點鏈表的增刪查改
void listModefiy(pNode_t *ppHead, int findNum, int changeNum)
{//這裏傳入的是二級指針,但因爲不用修改指針的指向,只需修改值,傳入一級指針也是可以的,然後在主函數中不用取地址傳入。(pNode_t pHead,int findNum,int changeNum),
pNode_t pCur = *ppHead;
while (pCur)
{
if (pCur->num == findNum)
{
pCur->num = changeNum;
break;
}
pCur = pCur->pNext;
}
if (pCur == NULL)
{
printf("there are't no value here");
}
}
鏈表的刪除:先檢查鏈表是否爲空,爲空返回,不爲空,則判斷首節點是否爲刪除的節點,如果是,將首指針向後移動並且保證首指針不指向NULL,還是設立pre和cur指針遍歷找到待刪除節點。最後記得free(pCur),pCur=NULL;避免懸空指針。
void deleteNum(pNode_t *ppHead,pNode_t *ppTail,int dNum)
{
pNode_t pCur = *ppHead;
if (pCur== NULL)
{
printf("This list is empty!\n");
return ;
}
else if(pCur->num==dNum)
{
*ppHead = pCur->pNext;
if (*ppHead == NULL)
{
*ppTail = NULL;
}
else
{
pNode_t pPre = *ppHead;
pCur = pPre->pNext;
while (pCur)
{
if (pCur->num == dNum)
{
pPre->pNext = pCur->pNext;
break;
}
pPre = pCur;
pCur = pCur->pNext;
}
if (pCur == *ppTail)
{
*ppTail = pPre;
}
if(pCur==NULL)
{
printf("There are not value here\n");
return;
}
}
free(pCur);
pCur == NULL;
}