Leetcode 206. Reverse Linked List

Description: Reverse a singly linked list.

Link: https://leetcode.com/problems/reverse-linked-list/

Examples:

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

思路: 乍一看很像24. Swap Nodes in Pairs这个题目, [1,2,3,4] -> [2,1,4,3], 是内部两两交换,这个题目其实也可以用这种想法[1,2,3,4,5], step1: [1] and [2] swap and link to [2,1], 记录[2,1]和[3,4,5]的头结点, step2: 将[2,1] and [3,4,5]看做两个node, repeat step1: [2,1] and [3] swap and link to [3,2,1], record the head node of [3,2,1] and [4,5], 一直做,直到结尾。

# 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 not head: return head
        if not head.next: return head
        
        p = head   # the reversed part head
        q = head.next # the head of part to reverse
        p.next = None  # first node will be the end after reversing
        while q:
            f = q.next
            q.next = p
            p = q
            q = f
        return p

日期: 2020-11-19  今天早点做完

原文地址:https://www.cnblogs.com/wangyuxia/p/14003650.html