The sword refers to offer 15. Reverse linked list (linked list)

Source: Internet
Author: User

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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.