题目链接
https://leetcode-cn.com/problems/reverse-linked-list/
题目
给你单链表的头节点
head
,请你反转链表,并返回反转后的链表。
示例
示例 1:
输入:head = [1,2,3,4,5]
输出:[5,4,3,2,1]
示例 2:
输入:head = [1,2]
输出:[2,1]
示例 3:
输入:head = []
输出:[]
思路
定义前后两个指针cur1和cur2,依次改变每个结点next的指向,从而实现链表的反转。
C++ Code
/**
* 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==nullptr||head->next==nullptr) return head;
//前后指针,依次反转结点指向
ListNode* cur1=head;
ListNode* cur2=nullptr;
while(cur1!=nullptr)
{
ListNode* temp=cur1->next;
cur1->next=cur2;
cur2=cur1;
cur1=temp;
}
return cur2;
}
};