- 反转链表
题目大意:
如题,反转链表
思路:
不开辟新空间,原地反转链表。
题解:
/**
* 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 == nullptr || head->next == nullptr)
return head;
ListNode* curr = nullptr;
ListNode* temp = new ListNode();
while(head != nullptr)
{
temp = head;
head = head->next;
//temp->next = new ListNode();
temp->next = curr;
curr = temp;
}
return curr;
}
};
/*
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(head == nullptr || head->next == nullptr)
return head;
ListNode* curr_next = head;
ListNode* temp = new ListNode();
head = head->next;
curr_next->next = nullptr;
while(head != nullptr)
{
temp = head;
head = head->next;
//temp->next = new ListNode();
temp->next = curr_next;
curr_next = temp;
}
return curr_next;
}
};
*/