程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Daily question python86: separate linked list

編輯:Python

subject : Give you a list of the head node head And a specific value x , Please separate the linked list , Make all Less than x All of the nodes appear in Greater than or equal to x Before the node . You should Retain The initial relative position of each node in the two partitions .

Example 1:

Input :head = [1,4,3,2,5,2], x = 3 Output :[1,2,2,4,3,5]
Example 2:

Input :head = [2,1], x = 2 Output :[1,2]

Tips :

The number of nodes in the linked list is in the range [0, 200] Inside
-100 <= Node.val <= 100
-200 <= x <= 200

Program description :
Create two dummy nodes , One is for storing ratio x Small number , A storage is greater than or equal to x Number of numbers , Then merge the two linked lists .( Suggest drawing to understand )
All the code :

# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def partition(self, head: ListNode, x: int) -> ListNode:
p = ListNode(0)
small = p
q = ListNode(0)
big = q
while head:
if head.val<x:
small.next = head
small = small.next
else:
big.next = head
big = big.next
head = head.next
big.next = None
small.next = q.next
return p.next

Title source : Power button (leetcode)


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved