Sword refers to Offer24-reverse linked list-easy

Question link

Title description:

Define a function, input the head node of a linked list, reverse the linked list and output the head node of the reversed linked list.

For example, enter:

输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL

data range:

0 <= 节点个数 <= 5000

Problem-solving ideas:

In fact, it is a process of turning around
1->2->3->4->5->NULL
NULL <- 1 <- 2 <-3 <- 4 <- 5
1. Set a node1 variable, the initial value is NULL , The initial value of node2 is head
node2 next points to node1
Insert picture description here
2. Node1 moves to the location of node2, node2 moves to the location of node2next, repeat steps 1
Insert picture description here
3. Until node2 is NULL, return to node1. The final result is as follows
Insert picture description here

AC code (c++)

/**
 * 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 * node1 = NULL;
        ListNode * node2 = head;
        while(node2){
    
    
            ListNode * nt = node2->next;
            node2->next = node1;
            node1 = node2;
            node2 = nt;
        }

        return node1;
    }
};

Guess you like

Origin blog.csdn.net/Yang_1998/article/details/113050937