力扣——206.反转链表

题目

力扣——206.反转链表_第1张图片

python代码

方法一:利用新列表,创建新的链表

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution(object):
    def reverseList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        valList=[]
        pointer=head
        while pointer:
            valList.append(pointer.val)
            pointer=pointer.next
        pointer=head
        while valList:
            pointer.val=valList.pop()
            pointer=pointer.next
        return head

在这里插入图片描述

方法二:双指针

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution(object):
    def reverseList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if head==None:
            return None
        left = right =head
        if right.next==None:
            return head
        else:
            right=right.next
            left.next=None
        while right!=None:
            head=right
            right=right.next
            head.next=left
            left=head
        return head

在这里插入图片描述

你可能感兴趣的:(数据结构与算法,python,leetcode,链表)