LeetCode刷题-206——Reverse Linked List(反转链表)

链接:

https://leetcode.com/explore/interview/card/top-interview-questions-easy/93/linked-list/560/

题目:

Reverse a singly linked list.

Example:

Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL

Notes:

分别用非递归和递归方式实现

解析:

思路是依次将从第二个结点到最后一个结点的后继设为头结点,然后将该节点设为头结点的后继(需记住将原头结点的后继设为空)。

解答:

非递归方式

# 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
        """
        p1 = None
        p2 = head
        while p2 is not None:
            temp = p2.next
            p2.next = p1
            #更新p1,p2值
            p1 = p2
            p2 = temp
        return p1

递归方式

# 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
        """

        return self._reverse(head)
    def _reverse(self,p1,p2 = None):
        if not p1:
            return p2
        temp = p1.next
        p1.next = p2
        return self._reverse(temp,p1)

关于头结点,头指针,开始节点的介绍可以参考:
https://blog.csdn.net/geekmanong/article/details/50072435

你可能感兴趣的:(LeetCode)