Leetcode 206.链表反转

题目描述

在这里插入图片描述

解题思路

首先想到再定义一个新的链表,但是觉得比较浪费空间。于是就想到去改变next指针的指向。

实现动画

在这里插入图片描述
图源:代码随想录

代码实现(C++)

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
 //双指针法
class Solution {
    
    
public:
    ListNode* reverseList(ListNode* head) 
    {
    
    
        ListNode* temp;
        ListNode* pre=nullptr;
        ListNode* curnode=head;
        while(curnode)
        {
    
    
            temp=curnode->next;
            curnode->next=pre;
            pre=curnode;
            curnode=temp;
        }
        return pre;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_45847364/article/details/121595202