zoukankan      html  css  js  c++  java
  • 编程练习反转链表

    Code Snippet
    1. #include <iostream>
    2.  
    3. #define Reverse2
    4.  
    5. using namespace std;
    6.  
    7. struct linka{
    8.     int data;
    9.     linka* next;
    10. };
    11.  
    12. void reverse(linka* &head)
    13. {
    14.     if(head == NULL)
    15.         return;
    16.  
    17.     linka* pPre = NULL;
    18.     linka* pCur = head;
    19.  
    20.     while(pCur != NULL)
    21.     {
    22.         linka* pNext = pCur->next;
    23.         pCur->next = pPre;
    24.         pPre = pCur;
    25.         pCur = pNext;
    26.     }
    27.  
    28.     head = pPre;
    29. }
    30.  
    31. linka* reverse2(linka* cur, linka*& head)
    32. {
    33.     if(cur == NULL || cur->next == NULL)
    34.     {
    35.         head = cur;
    36.         return cur;
    37.     }
    38.     else
    39.     {
    40.         linka* temp = reverse2(cur->next, head);
    41.         temp->next = cur;
    42.         return cur;
    43.     }
    44. }
    45.  
    46. int main()
    47. {
    48.     linka arrayTest[10];
    49.     for(int i = 0; i < 10; i++)
    50.     {
    51.         arrayTest[i].data = i;
    52.         arrayTest[i].next = arrayTest+ i +1;
    53.         cout<< arrayTest[i].data<<endl;
    54.     }
    55.     arrayTest[9].next = NULL;
    56.  
    57.     linka* phead = arrayTest;
    58.  
    59. #ifdef Reverse2
    60.     linka* cur = reverse2(phead, phead);
    61.     cur->next = NULL;
    62. #else
    63.     reverse(phead);
    64. #endif
    65.  
    66.     while(phead->next != NULL)
    67.     {
    68.         cout<< phead->data<<endl;
    69.         phead = phead->next;
    70.     }
    71.     cout<<phead->data<<endl;
    72. }
  • 相关阅读:
    HDU2026 首字母变大写
    HDU2026 首字母变大写
    Recursive Bubble Sort(递归冒泡排序)
    Recursive Bubble Sort(递归冒泡排序)
    Topological Sorting(拓扑排序)
    Topological Sorting(拓扑排序)
    HDU1870 愚人节的礼物【堆栈+输入输出】
    HDU1870 愚人节的礼物【堆栈+输入输出】
    HDU1233 还是畅通工程
    HDU1233 还是畅通工程
  • 原文地址:https://www.cnblogs.com/awpatp/p/1597027.html
Copyright © 2011-2022 走看看