【easy】206. Reverse Linked List 链表反转

时间:2023-12-24 11:19:19

链表反转,一发成功~

/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
//就地反转
if(head == NULL || head ->next == NULL)
return head;
ListNode* pre = head;
ListNode* cur = head->next;
ListNode* nxt = NULL; while (cur){
nxt = cur->next;
cur->next = pre;
pre = cur;
cur = nxt;
}
head->next = NULL;
head = pre;
return head;
}
};