24 is inscribed: reverse list (C ++)

Topic Address: https://leetcode-cn.com/problems/fan-zhuan-lian-biao-lcof/

Title Description

Definition of a function, the input node of a head of the list, and inverting the output inversion of the head node list after the list.

Examples of topics

Example:

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

Problem-solving ideas

Double pointer: double pointers and pre cur, respectively a front node of the current node and the current node traversed. Tmp specific operation defined temporal pointer, for storing the next node within the meaning of cur current pointer, i.e. tmp = cur-> next, and so the current pointer cur points pre, cur value is then given to pre, finally, the assignment tmp to cur, an operation carried out under the cur until the tail of the list.

Recursion: recursive recursive function to the last node in the list, the node as the inverted list the head node, then the function returns in each process, so that next current node to the next node of the current node , at the same time, let the current node's next point blank, in order to achieve the reverse operation of the list.

Reference article: https://leetcode-cn.com/problems/fan-zhuan-lian-biao-lcof/solution/fan-zhuan-lian-biao-yi-dong-de-shuang-zhi-zhen-jia/

Program source code

Double pointer

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        if(head == NULL) return head; //空链表
        ListNode* pre = nullptr;
        ListNode* cur = head;
        while(cur != nullptr)
        {
            ListNode* tmp = cur->next;
            cur->next = pre;
            pre = cur;
            cur = tmp;
        }
        return pre;
    }
};

Recursion

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* reverseList(ListNode* head) {
       if(head == NULL || head->next == NULL) return head;
       ListNode* rev = reverseList(head->next);
       head->next->next = head;
       head->next = NULL;
       return rev;
    }
};

Guess you like

Origin www.cnblogs.com/wzw0625/p/12536744.html