题目如下:
给你单链表的头节点 head
,请你反转链表,并返回反转后的链表。
提示:
- 链表中节点的数目范围是
[0, 5000]
-5000 <= Node.val <= 5000
解题思路:
将整个链表反转,可以在顺序扫描的过程中进行,将一个指针反向指示即可,这样的操作涉及到两个指针,但需要对指针进行更新,所以使用三个指针变量进行,pre、cur、next 。
代码如下:
/**
* 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) return head;
else{
ListNode *pre=NULL;
ListNode *cur=head;
while(cur){
ListNode *next=cur->next;
cur->next=pre;
pre=cur;
cur=next;
}
head=pre;
}
return head;
}
};
总结:
简单的链表操作