206.反转链表
采用 迭代方法
借用下另外位博主的图
首先定义三个节点
cur 当前节点
pre 反转后的下一个节点
temp 临时节点
先让pre中的指针指向null
cur 指向head
然后开始循环
每一次循环都使得cur的下一个节点中的地址为pre的地址,再让cur=cur.next 使得cur移动到下一个节点
画图演示一下
最开始 是这样的。有三个节点的单向链表
经过第一次循环 :
temp = cur->next;
cur->next = pre;
pre = cur;
cur=temp;
变成了这样 如图所示
重复以上操作 直至 head=最后一个非空temp
以下是AC代码
/**
* 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) {
ListNode* cur = head;
ListNode* pre = nullptr;
ListNode* temp;
while(cur!=nullptr)
{
temp = cur->next;
if(temp!=nullptr)
head = temp;
cur->next = pre;
pre = cur;
cur = temp;
}
return head;
}
};
//hsz你已经好久没表扬过我了!!!