链表
全部代码
#include <stdio.h> #include <stdlib.h> #include <assert.h> typedef struct node { int nValue; struct node * pNext; }MyList; void CreateList(MyList **ppHead) { MyList *pTemp = NULL; MyList *pTail = NULL; //the number of node int number; int i; //the value of node int value; assert(ppHead != NULL); printf("please input a number of the node :"); scanf("%d", &number); for(i=0; i<number; ++i) { printf("please input the %d value of node :", i+1); scanf("%d", &value); pTemp = (MyList *)malloc(sizeof(MyList)); if(NULL == pTemp) { printf("allocate space failed !\n"); exit(-1); } pTemp->nValue = value; pTemp->pNext = NULL; //add node if(NULL == *ppHead) { *ppHead = pTemp; } else { pTail->pNext = pTemp; } pTail = pTemp; } } void Traverse(MyList *pHead) { if(NULL == pHead) { printf("list is null\n"); return; } while(pHead != NULL) { printf("%d ", pHead->nValue); pHead = pHead->pNext; } } //reverse traverse void RecTraverse(MyList *pHead) { if(NULL == pHead) { return; } RecTraverse(pHead->pNext); printf("%d ", pHead->nValue); } //the inversion of list void Reverse(MyList **ppHead) { MyList *p1 = NULL; MyList *p2 = NULL; MyList *p3 = NULL; assert(ppHead != NULL); if(NULL==*ppHead || NULL==(*ppHead)->pNext) { return; } p2 = *ppHead; p3 = p2->pNext; while(p3 != NULL) { //change direction p2->pNext = p1; //handle the next node p1 = p2; p2 = p3; p3 = p2->pNext; } p2->pNext = p1; *ppHead = p2; } int main(void) { MyList *pHead = NULL; CreateList(&pHead); Traverse(pHead); printf("\n"); RecTraverse(pHead); printf("\n"); Reverse(&pHead); Traverse(pHead); printf("\n"); RecTraverse(pHead); printf("\n"); return 0; }
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步