循环遍历链表,将链表中的元素从表头依次取出指向新链表即可
三个变量,head是要维护的输出结果,orghead是定位变量,tempNode是用来赋值的中间变量
class ListNode:
def __init__(self,x):
self.val=x
self.next=None
class Solution(object):
def reverseList(self,head):
if not head:
return head
orghead=head
while orghead.next:
temp=orghead.next
orghead.next=orghead.next.next
temp.next=head
head=temp
return head
if __name__=="__main__":
head=ListNode(2)
head.next=ListNode(3)
head.next.next=ListNode(4)
su=Solution()
result=su.reverseList(head)
print(result.val,result.next.val,result.next.next.val)
对于类似于C中的指针的用法,一直没怎么搞明白,这里可以这样简单理解,当orgHead = head时,这两个变量本身的地址不同,但是是指向相同的东西,指针可以简单理解为指向哪一个,不用理解为赋值。。。