单向链表循环
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <malloc.h>
#include<assert.h>typedef struct LoopLink
{int nValue;struct LoopLink *pNext;
}LoopLink, *PLoopLink; //設置結點對象,包含兩個成員,nvalue和指向下一個對象的指針pNExtPLoopLink Create()
{PLoopLink pHead = (PLoopLink)malloc(sizeof(LoopLink)); //為表頭分配空間,用于存儲表頭if (NULL == pHead){printf("分配內存失敗!\n");}pHead->nValue = -9999;pHead->pNext = pHead; //為表頭中的數據成員進行賦值,,,nvalue,,和pnext指針return pHead; //返回 表頭給創建的對象
}void Insert(PLoopLink pHead, int nValue)
{if (NULL == pHead){printf("鏈表未創建成功!\n");return ;} //查看表頭是否創建,PLoopLink pCur = pHead;PLoopLink pTmp = (PLoopLink)malloc(sizeof(LoopLink)); //為插入的值(對象)開辟一個存儲空間,用于存儲nvalue和pnext指針pTmp->nValue = nValue; //為插入的對象的數據成員進行賦值pTmp->pNext = NULL;while (pCur->pNext != pHead){if (pCur->pNext->nValue > nValue){break;}pCur = pCur->pNext;}pTmp->pNext = pCur->pNext;pCur->pNext = pTmp; //插入操作,因為是按從小到大進行插值的,插入的對象的[nex指針指向的是大值得指針,
}void Delete(PLoopLink pHead, int nValue)
{if (pHead == NULL){printf("鏈表未創建成功!\n");return;}PLoopLink pCur = pHead;while (pCur->pNext!= pHead){if (pCur->pNext->nValue == nValue){PLoopLink pTmp = pCur->pNext;pCur->pNext = pTmp->pNext;free(pTmp); //釋放存儲空間pTmp = NULL; //表示該處沒有內存存儲數據}else{pCur = pCur->pNext;}}
}PLoopLink Find(PLoopLink pHead, int nValue)
{if (pHead == NULL){printf("鏈表未創建成功!\n");return NULL;}PLoopLink pCur = pHead; //首先,得到鏈表的首地址,進行查找while (pCur->pNext!= pHead) //退出循環的條件是最后的對象的pnext指向表頭,代表了循環到頭{if (pCur->pNext->nValue == nValue) //判斷對象的值是不是等于查找的值{return pCur->pNext; //如果是返回該處的地址}else{pCur = pCur->pNext; //如果不是,則進行下一個對象的查找 }}return NULL; //都沒有的話,返回NULL
}
bool IsEmpty(PLoopLink pHead)
{if (NULL == pHead){printf("鏈表未創建成功!\n");}return pHead->pNext == pHead;}void Print(PLoopLink pHead)
{if (pHead == NULL){printf("鏈表未創建成功!\n");return;}if (pHead->pNext == pHead){printf("鏈表為空!\n");return;} //循環結束的條件,對象的pnext指向表頭PLoopLink pCur = pHead->pNext;while (pCur != pHead){printf("%d ", pCur->nValue);pCur = pCur->pNext;}printf("\n");
}
int main()
{PLoopLink pHead = Create(); //鏈表的建立,主要是建立鏈表的表頭,為表頭開辟空間// printf("%d\n", IsEmpty(pHead));Insert(pHead, 1); //插值操作,主要是指在表頭后面,插入另一個對象,該對象的nvalue是輸入的值Insert(pHead, 5); Insert(pHead, 8);Insert(pHead, 4);Insert(pHead, 0);if (NULL != Find(pHead, 2)) //在鏈表中查找數值,一以鏈表的起始地址開始查找nvalue的值,用指針指向下一個對象,循環進行查找{printf("鏈表中有該數據!\n");}else{printf("鏈表中沒有該數據!\n");}Delete(pHead, 8); //刪除某一元素,就是讓該對象的上一個對象指向該對象的下一個對象,同時把該對象的存儲空間釋放Print(pHead); //打印鏈表中的數據,首先從表頭開始,然后指向下一個對象輸出值,然后指向下一個對象輸出。。。。。system("pause");return 0;
}
總結
- 上一篇: 鼠标马赛克图像部分区域
- 下一篇: 队列和数组