19.递归法和非递归法反转链表[ReverseLinkedList]

【题目】

输入一个链表的头结点,反转该链表,并返回反转后链表的头结点。

【非递归】

 C++ Code 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
 
listnode *Reverse_Iteratively(listnode *head)
{
    // prev <-cur  next->...->null
    listnode *prev = NULL;
    listnode *cur = head;
    listnode *next = 
NULL;
    
while(cur != NULL)
    {
        next = cur->next;
        cur->next = prev;
        
// update prev and cur
        prev = cur ;
        cur = next;
    }
    
return prev;
}

【递归】

 C++ Code 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
 
listnode *Reverse_Recursively(listnode *head)
{
    Reverse(NULL, head, NULL);
}

listnode *Reverse(listnode *prev, listnode *cur, listnode *next)
{
    
if (cur == NULL)
        
return prev;
    next = cur->next;
    cur->next = prev;
    prev = cur;
    cur = next;
    
return Reverse(prev, cur, next);
}

【参考】

http://zhedahht.blog.163.com/blog/static/2541117420073471124487/