Chinaunix首页 | 论坛 | 博客
  • 博客访问: 344052
  • 博文数量: 158
  • 博客积分: 52
  • 博客等级: 民兵
  • 技术积分: 613
  • 用 户 组: 普通用户
  • 注册时间: 2011-10-27 11:58
文章分类

全部博文(158)

文章存档

2017年(1)

2016年(5)

2015年(19)

2014年(8)

2013年(13)

2012年(80)

2011年(32)

分类: C/C++

2015-03-17 00:30:51

反转链表

  1. #include<stdio.h>

  2. struct ListNode{
  3.     int m_nKey;
  4.     struct ListNode* m_pNext;
  5. };

  6. void ReverseList(struct ListNode** pHead)
  7. {
  8.     struct ListNode *ReverseHead=NULL;
  9.     struct ListNode *pNode=*pHead;
  10.     struct ListNode *pPrev=NULL;
  11.     struct ListNode *pNext=NULL;
  12.     while(pNode!=NULL)
  13.     {
  14.         pNext=pNode->m_pNext;
  15.         if(pNext==NULL)
  16.             *pHead=pNode;
  17.         pNode->m_pNext=pPrev;
  18.         pPrev=pNode;
  19.         pNode=pNext;
  20.     }
  21.     return;
  22. }

  23. void ReverseListX(struct ListNode** pHead,struct ListNode *pNode,struct ListNode *pPrev)
  24. {
  25.     if(pNode!=NULL)
  26.     {
  27.         struct ListNode *pNext=pNode->m_pNext;
  28.         pNode->m_pNext=pPrev;
  29.         pPrev=pNode;
  30.         pNode=pNext;
  31.         ReverseListX(pHead,pNode,pPrev);
  32.     }
  33.     else
  34.         *pHead=pPrev;
  35. }

  36. void CreateList(struct ListNode **pHead)
  37. {
  38.     struct ListNode *tList=NULL;
  39.     int i=0;
  40.     for(;i<10;i++)
  41.     {
  42.         struct ListNode *temp=(struct ListNode *)malloc(sizeof(struct ListNode));
  43.         temp->m_nKey=i;
  44.         temp->m_pNext=NULL;    
  45.         if(tList==NULL)
  46.         {
  47.             tList=temp;
  48.             *pHead=tList;
  49.         }
  50.         else
  51.         {
  52.             tList->m_pNext=temp;
  53.             tList=tList->m_pNext;
  54.         }
  55.     }
  56.     return;
  57. }

  58. void ShowList(struct ListNode *pHead)
  59. {
  60.     struct ListNode *temp=pHead;
  61.     printf("show:\n");
  62.     while(temp!=NULL)
  63.     {
  64.         printf("%d ",temp->m_nKey);
  65.         temp=temp->m_pNext;
  66.     }
  67.     printf("\n");
  68. }

  69. int main()
  70. {
  71.     struct ListNode *pHead=NULL;
  72.     CreateList(&pHead);
  73.     ShowList(pHead);
  74. /*    ReverseList(&pHead);
  75.     ShowList(pHead);*/
  76.     ReverseListX(&pHead,pHead,NULL);
  77.     ShowList(pHead);
  78. //堆上分配内存的释放此处省略;
  79. }


阅读(686) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~