欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

LeetCode-206. 反转链表

程序员文章站 2024-03-04 09:11:05
...

206. 反转链表


反转一个单链表。

示例:

输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL

进阶:
你可以迭代或递归地反转链表。你能否用两种方法解决这道题?

解题思路:反转链表是一个十分经典的题目,配合三个指针,将链表节点依次移动到链表头部即可完成。PS:链表的操作大多是对指针的操作。

Python3代码如下:

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def reverseList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if not head:
            return None
        dummy = ListNode(0)
        dummy.next = head
        index1 = head
        index2 = head.next
        while index2:
            index3 = index2.next
            index2.next = index1
            dummy.next = index2
            index1 = index2
            index2 = index3
        head.next = None
        return dummy.next
        

LeetCode-206. 反转链表

相关标签: Easy