Title Description
Enter a linked list, invert the linked list, and output the table header of the new list.
Title Address
https://www.nowcoder.com/practice/75e878df47f24fdc9dc3e400ec6058ca?tpId=13&tqId=11168&rp=3&ru=/ta/ Coding-interviews&qru=/ta/coding-interviews/question-ranking
Ideas
Phead always points to the node to be flipped
Last point to the first node after flipping
Each reversal of a node, the next node of the Phead points to the Last,last point Phead to become the first node after the reversal, in the Phead forward a node until the end of none
Python
#-*-coding:utf-8-*-classListNode:def __init__(self, x): Self.val=x Self.next=None#unidirectional chain table node1:1->2->3Node1 = ListNode (1) Node2= ListNode (2) Node3= ListNode (3) Node4= ListNode (4) Node5= ListNode (5) Node1.next=Node2node2.next=Node3node3.next=Node4node4.next=Node5classSolution:#back to ListNode defreverselist (Self, phead):#Write code here if notPheador notPhead.next:returnPhead Last=None whilephead:temp=Phead.next Phead.next= Last=Phead Phead=Tempreturn Lastif __name__=='__main__': Origin=Node1Print('before reversal:', end =' ') whileOrigin:Print(Origin.val, end =' ') Origin=Origin.next Result=solution (). Reverselist (Node1)Print('\ nthe reversal:', end =' ') whileResult:Print(Result.val, end =' ') Result= Result.next
The sword refers to offer 15. Reverse linked list (linked list)