反转链表
遍历链表,把链表的每个节点依次逆置;
当头结点不为空时:
1. 备份头结点的下一个节点
2. 头结点的下一个节点更新为新的头结点
3. 新的头结点更新为头结点
4. 头结点更新为下一个节点
/**
* 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) {
ListNode *new_head = nullptr;
while(head)
{
ListNode *next = head->next;
head->next = new_head;
new_head = head;
head = next;
}
return new_head;
}
};