力扣刷題筆記:86.分隔連結串列(思路簡單、主要鍛鍊連結串列操作、完整題解程式碼及註釋)
阿新 • • 發佈:2021-01-26
題目:
86、分隔連結串列
給你一個連結串列和一個特定值 x ,請你對連結串列進行分隔,使得所有小於 x 的節點都出現在大於或等於 x 的節點之前。
你應當保留兩個分割槽中每個節點的初始相對位置。
示例:
輸入:head = 1->4->3->2->5->2, x = 3
輸出:1->2->2->4->3->5
題解思路:
本體本質就是將連結串列分為:
1.小於 x 部分的連結串列按照原始順序 記為 p
2.大於等於 x 部分的連結串列按照原始順序 記為 q
3.拼接兩個連結串列,p --> q
題解python程式碼:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def partition(self, head: ListNode, x: int) -> ListNode:
p=less=ListNode(0) #定義p、q是為了在更新中保留less和more的頭部,方便合併以及返回
q= more=ListNode(0)
while head:
if head.val<x:
less.next=head #更新less的next
less=less.next #更新less的頭
else:
more.next=head #同上
more=more.next
head=head.next
more.next=None #抹去head初始的next值
less.next=q.next #合併less和more
return p.next #抹去初始的頭部值 0
作者:JamLeon
連結:https://leetcode-cn.com/problems/partition-list/solution/si-lu-jian-dan-yi-kan-jiu-dong-xing-neng-uf9p/
來源:力扣(LeetCode)https://leetcode-cn.com/problems/partition-list/