[LeetCode] 206. Reverse Linked List

版权声明:转载请和我说。 https://blog.csdn.net/u010929628/article/details/89737933

题目内容

Reverse a singly linked list.

Example:

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

题目思路

这个就是基本的尾插法构建链表。


程序代码

# 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
        nh=ListNode(0)
        #p=nh
        while head:
            tmp=ListNode(head.val)
            tmp.next=nh.next
            nh.next=tmp
            head=head.next
        return nh.next
        
        

猜你喜欢

转载自blog.csdn.net/u010929628/article/details/89737933