23. Leetcode 86. 分隔链表 (链表-基础操作类-分隔链表)
生活随笔
收集整理的這篇文章主要介紹了
23. Leetcode 86. 分隔链表 (链表-基础操作类-分隔链表)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
給你一個鏈表的頭節點 head 和一個特定值 x ,請你對鏈表進行分隔,使得所有 小于 x 的節點都出現在 大于或等于 x 的節點之前。你應當 保留 兩個分區中每個節點的初始相對位置。示例 1:輸入:head = [1,4,3,2,5,2], x = 3
輸出:[1,2,2,4,3,5]
示例 2:輸入:head = [2,1], x = 2
輸出:[1,2]# 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:cur = headl1 = ListNode(0)l2 = ListNode(0)head1 = l1head2 = l2while cur !=None:if cur.val < x:l1.next = ListNode(cur.val)l1 = l1.nextelse:l2.next = ListNode(cur.val)l2 = l2.nextcur = cur.nextl1.next = head2.nextreturn head1.next
總結
以上是生活随笔為你收集整理的23. Leetcode 86. 分隔链表 (链表-基础操作类-分隔链表)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 22. Leetcode 237. 删除
- 下一篇: 23. Leetcode 24. 两两交