/**
* 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 || head -> next == NULL) return head;
ListNode* p = NULL; //反转链表的头节点
ListNode* q = head;
while(head != NULL){
head = head -> next; //head指针用于记录下一个节点的位置
q -> next = p;
p = q;
q = head;
}
return p;
}
};
Leetcode206. 反转链表
最新推荐文章于 2024-07-11 23:32:17 发布