leetcode:[206]反转链表
Reverse a singly linked list.
Example:
Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL
# Definition for singly-linked list.class ListNode: def __init__(self, x): self.val = x self.next = Noneclass Solution: """ 1->2->3->4->None new_head | None<-4<-3<-2<-1 new_head就是从None开始一直到原来链表的尾。 在反转的时候先记录下一个节点,然后将当前节点反转,然后将更新新的表头,再遍历下一个节点 """ def reverseList(self, head: ListNode) -> ListNode: new_head = None while head: # 记录下一个节点,因为等下反转当前节点之后就会丢失下一个节点 next_node = head.next # 反转当前节点。因为相对于head来说,new_head指向的是head的前一个节点 head.next = new_head # 更新新的表头 new_head = head # 将指针往后移动,这时就需要用到前面记录的节点 head = next_node # 最后new_head就是反转后的表头 return new_head
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。