What is the inversion method of python linked list
Reversal of python linked list
Reverse linked list
I give you the head node of the singly linked list, please reverse the linked list. And return the reversed linked list.
Input: head = [1,2,3,4,5]
Output: [5,4,3,2,1]
- ##Input: head = [1,2]
- Output: [2,1]
Example 3:
- Input :head = []
- Output: []
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
"""
解题思路:
1.新建一个头指针
2.遍历head链表,依次在新的头节点位置插入,达到反转的效果
"""
def reverseList(self, head: ListNode) -> ListNode:
# 循环
new_head = None
while head:
per = head.next # pre 为后置节点,及当前节点的下一个节点
head.next = new_head # 插入头节点元素
new_head = head # 把串起来的链表赋值给头指针
head = per # 向后移一个单位
return new_head # 返回一个新的链表
Copy after login
Python reversal linked list related skills# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: """ 解题思路: 1.新建一个头指针 2.遍历head链表,依次在新的头节点位置插入,达到反转的效果 """ def reverseList(self, head: ListNode) -> ListNode: # 循环 new_head = None while head: per = head.next # pre 为后置节点,及当前节点的下一个节点 head.next = new_head # 插入头节点元素 new_head = head # 把串起来的链表赋值给头指针 head = per # 向后移一个单位 return new_head # 返回一个新的链表
Given the head node pHead of a singly linked list (the head node has a value, for example, in the figure below, its val is 1), the length is n, after reversing the linked list, return the head of the new linked list. Requirements: Space complexity O(1)O(1), time complexity O(n)O(n).
{1,2,3}Return value:
{3,2,1}Let’s first look at the most basic reverse linked list code:
# -*- coding:utf-8 -*- # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: # 返回ListNode def ReverseList(self, pHead): # write code here cur = pHead pre = None while cur: nextNode = cur.next cur.next = pre pre = cur cur = nextNode return pre
- cur: The head node of the original linked list. At the end of the inversion, cur points to the next node of pre
- pre: The tail node of the original linked list is the head node of the reversed linked list. The final return is pre.
- while cur: Indicates the condition for reversing the loop, here is to determine whether cur is empty. You can also change it to other loop conditions according to the conditions of the question
- Reverse the tail node of the linked list. The tail node here is None, and explicit specification will be mentioned later.
Next, let’s give two examples:
Reversing the specified interval in the linked listInverting every k nodes in the linked listSpecified interval reversal in the linked listReversing the interval between the m position and the n position of a linked list with a node number of size requires time complexity O(n) and space complexity O(1 ).Requirements: time complexity O(n), space complexity O(n)
Advanced: time complexity O(n), space complexity O (1)Input:{1,2,3,4,5},2,4Return value:
{1,4,3,2,5}
Apply the formula
The difference between this question and baseline is that Change the reversal of the entire linked list to the reversal of the interval between the m position and the n position of the linked list. Let's apply the formula:- The head node of the original linked list: cur: starting from head , then take m-1 steps to reach cur
- The tail node of the original linked list: pre: The node in front of cur
- Reverse loop condition : for i in range(n,m)
- Reverse the tail node of the linked list: you need to save it starting from head, then go m-1 steps, when you reach cur, at this time pre position prePos. prePos.next is the tail node of the reverse linked list.
- needs to be saved and started from head. , take m-1 steps again, and when you reach cur, the position of pre at this time is prePos. After the reversal cycle ends, start threading again
- Since the entire linked list is not reversed, it is best to create a new virtual head node dummyNode, and dummyNode.next points to the entire linked list
Code implementation
First look at the code of the formula part:# 找到pre和cur i = 1 while i<m: pre = cur cur = cur.next i = i+1 # 在指定区间内反转 preHead = pre while i<=n: nextNode = cur.next cur.next = pre pre = cur cur = nextNode i = i+1
nextNode = preHead.next preHead.next = pre if nextNode: nextNode.next = cur
class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def reverseBetween(self , head , m , n ): # write code here dummpyNode = ListNode(-1) dummpyNode.next = head pre = dummpyNode cur = head i = 1 while i<m: pre = cur cur = cur.next i = i+1 preHead = pre while i<=n: nextNode = cur.next cur.next = pre pre = cur cur = nextNode i = i+1 nextNode = preHead.next preHead.next = pre if nextNode: nextNode.next = cur return dummpyNode.next
Requires space complexity O(1), time complexity O(n)
Input:{1,2, 3,4,5},2Return value:
{2,1,4,3,5}
Apply formula
The difference between this question and the baseline is that the inversion of the entire linked list is changed to a group of k inversions. If the number of nodes is not a multiple of k, the remaining The nodes remain as they are. Let’s look at it in sections first. Suppose we face a linked list from position 1 to position k:- The head node of the original linked list: cur: start from head and go k -1 step to reach cur
原链表的尾节点:pre:cur前面的节点
反转循环条件:for i in range(1,k)
反转链表的尾节点:先定义tail=head,等反转完后tail.next就是反转链表的尾节点
先看下套公式部分的代码:
pre = None cur = head tail = head i = 1 while i<=k: nextNode = cur.next cur.next = pre pre = cur cur = nextNode i = i+1
这样,我们就得到了1 位置1-位置k的反转链表。
此时:
pre:指向反转链表的头节点
cur:位置k+1的节点,下一段链表的头节点
tail:反转链表的尾节点
那么,得到位置k+1-位置2k的反转链表,就可以用递归的思路,用tail.next=reverse(cur,k)
需要注意:如果链表中的节点数不是 k 的倍数,将最后剩下的节点保持原样
i = 1 tmp = cur while i<=k: if tmp: tmp = tmp.next else: return head i = i+1
代码实现
完整代码:
class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def reverseKGroup(self , head , k ): # write code here return self.reverse(head, k ) def reverse(self , head , k ): pre = None cur = head tail = head i = 1 tmp = cur while i<=k: if tmp: tmp = tmp.next else: return head i = i+1 i = 1 while i<=k: nextNode = cur.next cur.next = pre pre = cur cur = nextNode i = i+1 tail.next = self.reverse(cur, k) return pre
好了,抓住几个关键点:
cur:原链表的头节点,在反转结束时,cur指向pre的下一个节点
pre:原链表的尾节点,也就是反转后链表的头节点。最终返回的是pre。
while cur:表示反转循环的条件,这里是判断cur是否为空。也可以根据题目的条件改成其他循环条件
反转链表的尾节点,这里的尾节点是None,后面会提到显式指定。
The above is the detailed content of What is the inversion method of python linked list. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

Docker uses Linux kernel features to provide an efficient and isolated application running environment. Its working principle is as follows: 1. The mirror is used as a read-only template, which contains everything you need to run the application; 2. The Union File System (UnionFS) stacks multiple file systems, only storing the differences, saving space and speeding up; 3. The daemon manages the mirrors and containers, and the client uses them for interaction; 4. Namespaces and cgroups implement container isolation and resource limitations; 5. Multiple network modes support container interconnection. Only by understanding these core concepts can you better utilize Docker.

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.
