編程練習-反轉鏈表

來源:互聯網
上載者:User
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. }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.