题目链接:https://leetcode-cn.com/problems/reverse-linked-list/
题目如下:
思路(双指针法):
/**
* 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=head;
ListNode* pre=NULL;
while(cur!=NULL){
ListNode* temp=cur->next;//保存cur的下一个节点,因为接下来要改变cur->next
cur->next=pre;//反转操作
pre=cur;cur=temp;//更新pre和cur指针
}
return pre;
}
};