反转链表
思路:很简单的题目,开始以为要先遍历到最后一个,然后记前一个点的地址,再修改;及第一次遍历找到 5 和4 的地址,然后5->next=4;第二次找到4 3,4->next=3;但是这样很傻。
第二种 map 记录第几个数和地址 5->next=map.find(第4个的val值)
第三种 ,突然灵感来了,记录第一个值 first 记录之后的值 second;
while(second!=nullptr)
一定要先定义一个temp记录second->next,因为等会要反转链表了,反转之后的second->next就不是原来的那个后面的元素地址了;
temp=second->next;
second->next=first;
first=second;
second=temp;
代码如下:`
/**
* 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) return head;
//判断是否只有一个节点
if(head->next==nullptr) return head;
//如果是两节点以上
ListNode* first,* second;
ListNode* temp=nullptr;
//记录当前节点与下一个节点
first=head;
second=first->next;
first->next=nullptr;
while(second!=nullptr)
{
temp=second->next;
second->next=first;
first=second;
second=temp;
}
return first;
}
};