单链表倒置
发布时间:2020-12-13 19:44:37 所属栏目:百科 来源:网络整理
导读:#include stdlib.h#include stdio.hstruct Node{int iValue;struct Node* pNext;};typedef struct Node Node;Node* RevList( Node* pHeader ){if( !pHeader )return NULL;Node* pRes = pHeader;//保存结果Node* pCur = pHeader;//当前处理节点Node* pNext =
#include <stdlib.h> #include <stdio.h> struct Node { int iValue; struct Node* pNext; }; typedef struct Node Node; Node* RevList( Node* pHeader ) { if( !pHeader ) return NULL; Node* pRes = pHeader;//保存结果 Node* pCur = pHeader;//当前处理节点 Node* pNext = pHeader->pNext;//下一节点 pRes->pNext = NULL;//首节点下一节点置空 //算法如下:取当前节点保存其后续节点 断开当前节点到结果链表的首部 while( pNext ) { pCur = pNext; pHeader = pNext->pNext; pCur->pNext = pRes; pNext = pHeader; pRes = pCur; } return pRes; } void PrintList( Node* const pHeader ) { Node* pCur = pHeader; while( pCur ) { printf( "%d ",pCur->iValue ); pCur = pCur->pNext; } puts( "" ); } int main( int argc,char** argv ) { Node* pHeader = (Node*)malloc( sizeof( Node ) ); Node* pCur = pHeader; pCur->iValue = 1; pCur->pNext = (Node*)malloc( sizeof( Node ) ); pCur = pCur->pNext; pCur->iValue = 2; pCur->pNext = (Node*)malloc( sizeof( Node ) ); pCur = pCur->pNext; pCur->iValue = 3; pCur->pNext = NULL; PrintList( pHeader ); pHeader = RevList( pHeader ); PrintList( pHeader ); puts( "" ); return 0; } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |