自学内容网 自学内容网

【LeetCode】86.分割链表

1. 题目

在这里插入图片描述

2. 分析

这题没有太大难度,主要是熟悉代码。

3. 代码

# 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: Optional[ListNode], x: int) -> Optional[ListNode]:
        lower_head = None
        lower_head_bak = None
        upper_head = None
        upper_head_bak = None
        
        if head is None:
            return None
        while(head):
            tmp = head.next
            if head.val < x:
                if lower_head:
                    lower_head.next = head
                else:
                    lower_head_bak = head
                lower_head = head # 更新结果
                lower_head.next = None
            else:
                if upper_head is None:
                    upper_head_bak = head
                else:
                    upper_head.next = head
                upper_head = head
                upper_head.next = None
            head = tmp
        if lower_head :
            lower_head.next = upper_head_bak
            return lower_head_bak
        elif lower_head is None and upper_head_bak:
            return upper_head_bak

原文地址:https://blog.csdn.net/liu16659/article/details/140649147

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!