NC78: 反转链表
python代码
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def print_list(self):
while self.next is not None:
print(self.val)
self = self.next
print(self.val)
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
# @param head ListNode类
# @return ListNode类
#
class Solution:
def ReverseList(self , head: ListNode) -> ListNode:
# write code here
if head is None:
rhead = head
elif head.next is None:
rhead = head
else:
p = head
q = head.next
n = q.next
p.next = None
while n is not None:
q.next = p
p = q
q = n
n = n.next
q.next = p
rhead = q
return rhead
if __name__ == '__main__':
head = ListNode(1)
# head1 = ListNode(2)
# head.next = head1
# head2 = ListNode(3)
# head1.next = head2
ListNode.print_list(head)
a = Solution()
rhead = Solution.ReverseList(a, head)
ListNode.print_list(rhead)
主要思路就是利用,三个游标依次向后移动,每次都是反转一个指针,但是要考虑到特殊的情况,链表为空,链表只有一个结点,链表没有结点,和正常链表的三种情况,并且在第三章情况,跳出while循环的时候,注意条件是n is none 不是n.next is None