Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to reverse the linked list with python

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)05/31 Report--

Most people do not understand the knowledge points of this article "python how to reverse the linked list", so the editor summarizes the following contents, detailed content, clear steps, and has a certain reference value. I hope you can get something after reading this article. Let's take a look at this "how to reverse the linked list python" article.

[title]

Reverses a single linked list.

Example:

Enter: 1-> 2-> 3-> 4-> 5-> NULL

Output: 5-> 4-> 3-> 2-> 1-> NULL

Advanced:

You can iterate or recursively reverse the linked list. Can you solve the problem in two ways?

[ideas]

Use three pointers p, Q, r to point to three adjacent nodes, where p.next is qmenq.next is r.

Modify the pointer to Q and move the three pointers p, Q and r, that is, q.next = pforce p = Q, Q = r r = r.next. Continuous circulation, and pay attention to modify head.next and head, the list can be flipped.

[code]

Python version

# Definition for singly-linked list.

# class ListNode:

# def _ _ init__ (self, val=0, next=None):

# self.val = val

# self.next = next

Class Solution:

Def reverseList (self, head: ListNode)-> ListNode:

# head is empty

If not head:

Return head

# p, Q, r are three adjacent nodes

# q.next points to p, while three pointers move backward

P, Q, r = head, head.next, head

While q:

R = q.next

Q.next = p

P = Q

Q = r

# modify head.next and head

Head.next = None

Head = p

Return p above is about the content of this article on "how to reverse the linked list in python". I believe we all have some understanding. I hope the content shared by the editor will be helpful to you. If you want to know more about the relevant knowledge, please pay attention to the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report