反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
代码:
v.1
知道结构以后就很简单了,这是最简单的迭代。然而递归方式我还没有看懂。
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution: def reverseList(self, head): """ :type head: ListNode :rtype: ListNode """ pre = None while head is not None: temp = head.next head.next = pre pre = head head = temp return pre
v2.0
class Solution: def reverseList(self, head): """ :type head: ListNode :rtype: ListNode """ if not head or not head.next: return head p = self.reverseList(head.next) head.next.next = head head.next = None return p