单链表反转的非递归与递归算法

template <typename T>
class ListNode{
 public:
  ListNode *next;   
  T     elements;
};

非递归
ListNode *ReverseList1(ListNode *root)
{
    ListNode *link,*prev=nullptr;
    while(root){
        link=root->next;
        root->next=prev;
        prev=root;
        root=link; 
    }
    return prev;
}

递归

ListNode *ReverseList2(ListNode *pre, ListNode *cur)  
{  
    if(!cur)  
        return pre;  
       
    ListNode *link = cur->next;  
    cur->next = pre;  
    return ReverseList2(cur,link);      
}



你可能感兴趣的:(单链表反转的非递归与递归算法)