剑指offer:24.反转链表

剑指offer:24.反转链表
定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL

解析(c++):
双指针
时间复杂度:o(n)
空间复杂度:o(n)

class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        if (head == NULL) {
            return head;
        }
        ListNode *cur = head;
        while (head -> next != NULL) {
            ListNode *t = head -> next ->next;
            head -> next -> next = cur;
            cur = head -> next;
            head -> next = t;
        }
        return cur;
    }
};

猜你喜欢

转载自blog.csdn.net/qq_36156649/article/details/107953289