(Leetcode) -c list reverse language

Reverse a singly linked list.

Example:

Input: 1-> 2-> 3-> 4- > 5-> NULL 
Output: 5-> 4-> 3-> 2- > 1-> NULL

Iterative method, as follows:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* reverseList(struct ListNode* head){
    if (head == NULL || head->next == NULL)
        return head;
    
    struct ListNode *pre = head;
    struct ListNode *cur = head->next;
    struct ListNode *tmp = head->next->next;
    
    while(cur)
    {
        tmp = cur->next;
        cur->next = pre;
        pre = cur;
        cur = tmp;
    }
    head->next = NULL;
    
    return pre;

}

Recursive method is as follows:

struct ListNode* reverseList(struct ListNode* head){
    if (head == NULL || head->next == NULL)
        return head;
    else
    {
        struct ListNode *newhead = reverseList(head->next);
        head->next->next = head;
        head->next = NULL;
        return newhead;
        
    }
}

Under summary, recursive writing, as a whole, can be divided into two portions recursive, one, recursive innermost layer is determined, then for this question, recursion is the innermost layer when the head is empty, or head- > next is empty. Then write the second portion, starting from the outermost layer, and it is assumed, the remaining part is passed recursive function returns the list has been inverted, and then do the rest. A recursive function is to be noted that a head tail, and a middle portion can be completed by the recursion.

Guess you like

Origin www.cnblogs.com/xingmuxin/p/11304359.html