题目要求:思路:定义一个新的head:myhead将myhead的下一个点标记为mynext每次让myhead的下一个点指向一个新的节点,新节点的下一个点指向mynext遍历链表,直到链表为空核心代码:#newheadNodemyhead=ListNode()#标记head节点的nextmynext=myhead.next#遍历链表的当前值为curcur=head#下一个要插入到新链表中的节点listiscur.nextcurnext=head.next#当前节点不为空when:whilecur:#将当前遍历节点的next指向新链表的mynextcur.next=mynext#head的next新链表指向当前节点myhead.next=cur#更新mynext的值,因为每次插入都是在新的head之后插入mynext=myhead.next#更新cur的值到下一个要插入的节点cur=curnext#如果curnext不为空,则curnext指向原链接的下一个节点listifcurnext:curnext=curnext.next#返回新链表头部的下一个节点returnmyhead.next完整代码:加上判断给定链表是否为空的条件#单向链表的定义。#classListNode(object):#def__init__(self,x):#self.val=x#self.next=Noneclass解决方案(object):defreverseList(self,head):""":typehead:ListNode:rtype:ListNode"""如果head为None:返回Nonemyhead=ListNode()mynext=myhead.nextcur=headcurnext=head.nextwhilecur:cur.next=mynextmyhead.next=curmynext=myhead.nextcur=curnext如果curnext:curnext=curnext.next返回myhead.next
