导航

数据结构基础 -- 反转链表

Posted on 2022-07-09 10:32  wuqiu  阅读(27)  评论(0编辑  收藏  举报

所需开辟的变量

三个链表节点的指针,分别指向前一个节点,当前节点,以及当前节点的下一个节点

所需要注意的事情

1.每一次只改变一个指针
2.head节点之前要有一个nullpter指针

反转链表

给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。


class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        ListNode* behind = nullptr;
        ListNode* node = head;
        while(node != nullptr){
            ListNode* front = node->next; // 取下一个节点
            node->next = behind; //改变指针指向
            behind = node; // 向前移动
            node = front;
        }
        return behind;
    }
};