【剑指offer】【链表】24.反转链表

题目链接:https://leetcode-cn.com/problems/fan-zhuan-lian-biao-lcof/

指针

遍历链表,把链表的每个节点依次逆置;
当头结点不为空时:
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;
    }
};
posted @ 2020-04-06 21:19  NaughtyCoder  阅读(93)  评论(0)    收藏  举报