zoukankan      html  css  js  c++  java
  • 206. Reverse Linked List

    Reverse a singly linked list.

    Example:

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

    Follow up:

    A linked list can be reversed either iteratively or recursively. Could you implement both?

    Solution1:

    # Definition for singly-linked list.
    class ListNode:
        def __init__(self, x):
            self.val = x
            self.next = None
    
    class Solution:
        def reverseList(self, head):
            """
            :type head: ListNode
            :rtype: ListNode
            """
            start = None
            while head:
                temp = head
                head = head.next
                temp.next = start
                start = temp
            return start
    

    Solution2:

    # Definition for singly-linked list.
    class ListNode:
        def __init__(self, x):
            self.val = x
            self.next = None
    
    class Solution:
        def reverseList(self, head):
            """
            :type head: ListNode
            :rtype: ListNode
            """
            p = head
            num = []
            while p:
                num.append(p.val)
                p = p.next
            p = head
            print(num)
            while len(num):
                p.val = num.pop()
                p = p.next
            return head
    

    或许第二种方法更好写?

  • 相关阅读:
    Vim使用
    软件测试基础知识
    数字成像系统
    linux操作系统运行学习总结
    python算法学习总结
    Django Rest Framework框架
    mysql学习笔记一
    学习方法
    算法模板汇总
    习题练习1
  • 原文地址:https://www.cnblogs.com/bernieloveslife/p/9736744.html
Copyright © 2011-2022 走看看