【leetcode】反转链表c++

题目描述:
给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。
示例1:
在这里插入图片描述

输入:head = [1,2]
输出:[2,1]

示例2:
在这里插入图片描述

输入:head = [1,2,3,4,5]
输出:[5,4,3,2,1]

示例3:

输入:head = []
输出:[]

代码:

/**
 * 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) {
    
    
        if(head==NULL)return NULL;
        ListNode* node=NULL;
        ListNode* temp=head;
        ListNode* temp1=head;
        while(true){
    
    
            if(temp->next==NULL){
    
    
                temp1=temp;
                temp1->next=node;
                break;
            }
            temp1=temp; //因为先对temp1赋值,再移动temp,所以当temp移动到链表尾部,temp1还未赋值为temp就已经结束,需要补上temp->next==NULL时对temp1的处理
            temp=temp->next;
            temp1->next=node;
            node=temp1;
        }
        return temp1;
    }
};

自己画图理清即可。

因为每次反转后,无法调用next向后移动原链表的当前指针temp(next经过反转已经指向原链表反方向了),所以需要一个记录原temp->next位置的指针temp1,node来记录当前指针temp反转后需要指向的位置。

原链表中node、temp、temp1的位置关系:
node—>temp—>temp1

猜你喜欢

转载自blog.csdn.net/qq_40315080/article/details/116138656