leetcode -86 分割链表

题目:https://leetcode-cn.com/problems/partition-list/
解题思路
此处撰写解题思路
这道题目的意思就是让把比X小的数字放到前面 比X大的数字放到后面;
这里我们初始化两个虚拟节点,为min_head max_head 并保存头节点为a,b
这里逻辑上非常要注意的是 a,b是不能在动的 应为题目要求返回两个头节点,所以只能给max_head,min_head动

代码

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:
min_head = ListNode(0)
max_head= ListNode(0)
a = min_head
b = max_head
while head:
if head.val < x:
min_head.next = ListNode(head.val)
min_head= min_head.next #每一次赋值之后都要将指针指到最后一个节点,方便下次直接赋值
else:
max_head.next = ListNode(head.val)
max_head = max_head.next
head = head.next
min_head.next =b.next #这里将大于X的节点赋值给小于X的末尾
return a.next

作者:vigilant-7amportprg
链接:https://leetcode-cn.com/problems/partition-list/solution/python3jie-shi-by-vigilant-7amportprg-5wxm/

你可能感兴趣的:(leetcode -86 分割链表)