力扣热题100 - 常见面试题,我的腾讯客户端一面 - 链表:反转链表

题目描述:

题号:206

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

图片

 

解题思路:

思路一:双指针迭代

算法思路:

在遍历链表时,将当前节点的 next 指针改为指向前一个节点。

因此需要:1、储存当前节点的前一个节点  2、储存当前节点的后一个节点

时间复杂度:O(N)

空间复杂度:O(1)

C++


// C++
/**
 * 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) {
        if(head == nullptr || head->next == nullptr) {
            return head;
        }
        ListNode *cur = head, *pre = nullptr;
        while(cur != nullptr) {
            ListNode *temp = cur->next;
            // 使当前节点指向前一个节点
            cur->next = pre;
            // 准备处理下一个节点
            // 两指针都向前移动一个元素
            pre = cur;
            cur = temp;
        }
        return pre;
    }
};

go

// go
/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */
func reverseList(head *ListNode) *ListNode {
    if head == nil || head.Next == nil {
        return head
    }
    var pre *ListNode
    cur := head
    for cur != nil {
        temp := cur.Next
        // 使当前指针指向它的前一个节点
        cur.Next = pre
        // 两指针都向前移动一个元素
        pre = cur
        cur = temp
    }
    return pre
}

思路二:递归

思路关键点:假设后面的链表都已经反转完成了,该如何翻转当前节点?(函数调用栈是先进后出的,因此是链表的后半部分先被反转)

解决思路:假设当前节点是 2

原链表:1 -> 2 -> 3 -> 4 -> 5

当前函数递归的链表:1 -> 2 -> 3 <- 4 <- 5

需要节点 3 的 next 指针指向 2,即 3 -> next 指向 2,即 2 -> next -> next 指向 2 ( 3 是 2 的 next )

时间复杂度:O(N)

空间复杂度:O(1)

C++


// C++
/**
 * 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) {
        // 递归结束条件
        if(head == nullptr || head->next == nullptr) {
            return head;
        }
        ListNode* newHead = reverseList(head->next);
        head->next->next = head;
        head->next = nullptr;
        return newHead;
    }
};

go


// go
/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */
func reverseList(head *ListNode) *ListNode {
    // 递归结束条件
    if head == nil || head.Next == nil {
        return head
    }
     newHead := reverseList(head.Next)
    head.Next.Next = head
    head.Next = nil
    return newHead
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值