[数据结构]单链表反转

  1. 37 LinkList reverse_link(LinkListlist)  
  2. 38 {  
  3. 39    if(NULL == list  
  4. 40            || NULL == list->next)  
  5. 41        return list;  
  6. 42  
  7. 43  
  8. 44    LinkList temp,prev,next;  
  9. 45  
  10. 46    prev = list;  
  11. 47    temp = list->next;  
  12. 48    prev->next = NULL;  
  13. 49       
  14. 50    while(temp != NULL)  
  15. 51    {     
  16. 52        next = temp->next;  
  17. 53        temp->next = prev;  
  18. 54        prev = temp;  
  19. 55        temp = next;  
  20. 56     }  
  21. 57    return prev;  
  22. 58 }  


 

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
 
    1. ListNode* ReverseIteratively(ListNode* pHead)  
    2. {  
    3.        ListNode* pReversedHead = NULL;  
    4.        ListNode* pNode = pHead;  
    5.        ListNode* pPrev = NULL;  
    6.       while(pNode != NULL)  
    7.        {  
    8.             // get the next node, and save it at pNext  
    9.              ListNode* pNext = pNode->m_pNext;  
    10.             // if the next node is null, the currect is the end of original   
    11.             // list, and it's the head of the reversed list  
    12.             if(pNext == NULL)  
    13.                    pReversedHead = pNode;  
    14.   
    15.             // reverse the linkage between nodes  
    16.              pNode->m_pNext = pPrev;  
    17.   
    18.             // move forward on the the list  
    19.              pPrev = pNode;  
    20.              pNode = pNext;  
    21.        }  
    22.   
    23.       return pReversedHead;  
    24. }  
原文地址:https://www.cnblogs.com/zhiliao112/p/4237160.html