反转链表-链表206-python&C++

解题思路

在这里插入图片描述
在这里插入图片描述

Python

# Definition for singly-linked list.
class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next
class Solution:
    def reverseList(self, head):
        pre = None
        cur = head
        while cur:
            temp = cur.next
            cur.next = pre
            pre = cur
            cur = temp
        return pre

C++

class Solution {
    
    
public:
    ListNode* reverseList(ListNode* head) {
    
    
        ListNode * curr = head;
        ListNode * pre = nullptr;
        ListNode * temp = curr;
        while(curr){
    
    
            curr = curr->next;
            temp->next = pre;
            pre = temp;
            temp = curr;
        }
        return pre;
    }
};

复杂度分析:

  • 时间复杂度:O(n),其中 n 是链表的长度。需要遍历链表一次;
  • 空间复杂度:O(1)。

猜你喜欢

转载自blog.csdn.net/VaccyZhu/article/details/113786830