Leetcode基础学习-Python2实现反转链表
2020-02-24 本文已影响0人
时间煮菜
反转链表
反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL
输出: 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 head == None:
return head
pre = head
cur = head.next
pre.next = None
while cur:
temp = cur.next
cur.next = pre
pre = cur
cur = temp
return pre
if __name__ == "__main__":
head = ListNode(1)
p1 = ListNode(2)
p2 = ListNode(3)
p3 = ListNode(4)
p4 = ListNode(5)
head.next = p1
p1.next = p2
p2.next = p3
p3.next = p4
p = Solution()
p = p.reverseList(head)
while p:
print p.val
p = p.next
运行截图
![](https://img.haomeiwen.com/i15729314/9ed24014f5e08368.png)