题目要求:
给你单链表的头节点 head
,请你反转链表,并返回反转后的链表。
示例 1:
输入:head = [1,2,3,4,5] 输出:[5,4,3,2,1]
解题思路:
使用双指针,pre在前,cur在后,让pre指向cur,实现局部反转,再将两个指针都向后移动直到pre到尾部
代码展示:
/**
* 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* cur = NULL,*pre = head;
while(pre!=NULL){
ListNode* t=pre->next;
pre->next=cur;
cur=pre;
pre=t;
}
return cur;
}
};
运行结果: