题解 | #反转链表#
反转链表
http://www.nowcoder.com/practice/75e878df47f24fdc9dc3e400ec6058ca
-- coding:utf-8 --
class ListNode:
def init(self, x):
self.val = x
self.next = None
class Solution:
# 返回ListNode
def ReverseList(self, pHead):
# write code here
'''
#方法1:直接建立新的链表,然后使用头插法逆置
head=ListNode(0)
head.next=None
p=pHead
while p:
s=ListNode(p.val)
s.next=head.next
head.next=s
p=p.next
return head.next
'''
#方法2:直接使用头插法,在原表上进行逆置
head=ListNode(0)
head.next=None
p=pHead
while p:
s=p.next
p.next=head.next
head.next=p
p=s
return head.next