反转链表
- #include<stdio.h>
-
- struct ListNode{
- int m_nKey;
- struct ListNode* m_pNext;
- };
-
- void ReverseList(struct ListNode** pHead)
- {
- struct ListNode *ReverseHead=NULL;
- struct ListNode *pNode=*pHead;
- struct ListNode *pPrev=NULL;
- struct ListNode *pNext=NULL;
- while(pNode!=NULL)
- {
- pNext=pNode->m_pNext;
- if(pNext==NULL)
- *pHead=pNode;
- pNode->m_pNext=pPrev;
- pPrev=pNode;
- pNode=pNext;
- }
- return;
- }
-
- void ReverseListX(struct ListNode** pHead,struct ListNode *pNode,struct ListNode *pPrev)
- {
- if(pNode!=NULL)
- {
- struct ListNode *pNext=pNode->m_pNext;
- pNode->m_pNext=pPrev;
- pPrev=pNode;
- pNode=pNext;
- ReverseListX(pHead,pNode,pPrev);
- }
- else
- *pHead=pPrev;
- }
-
- void CreateList(struct ListNode **pHead)
- {
- struct ListNode *tList=NULL;
- int i=0;
- for(;i<10;i++)
- {
- struct ListNode *temp=(struct ListNode *)malloc(sizeof(struct ListNode));
- temp->m_nKey=i;
- temp->m_pNext=NULL;
- if(tList==NULL)
- {
- tList=temp;
- *pHead=tList;
- }
- else
- {
- tList->m_pNext=temp;
- tList=tList->m_pNext;
- }
- }
- return;
- }
-
- void ShowList(struct ListNode *pHead)
- {
- struct ListNode *temp=pHead;
- printf("show:\n");
- while(temp!=NULL)
- {
- printf("%d ",temp->m_nKey);
- temp=temp->m_pNext;
- }
- printf("\n");
- }
-
- int main()
- {
- struct ListNode *pHead=NULL;
- CreateList(&pHead);
- ShowList(pHead);
- /* ReverseList(&pHead);
- ShowList(pHead);*/
- ReverseListX(&pHead,pHead,NULL);
- ShowList(pHead);
- //堆上分配内存的释放此处省略;
- }