描述
翻转一个链表
样例
给出一个链表1->2->3->null,这个翻转后的链表为3->2->1->null
挑战
在原地一次翻转完成
分析
将原链表的第1个值取出,然后放在新链表的末端
然后再取出第二个,将其与刚刚的新链表再次组合
代码
"""
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
"""
class Solution:
"""
@param head: n
@return: The new head of reversed linked list.
"""
def reverse(self, head):
# write your code here
new_head = None
while head:
f, head = head.val, head.next
new_head = ListNode(f,new_head)
return new_head