LeetCode 86 Partition List (Python详解及实现)
来源:互联网 发布:域名需要购买解析吗 编辑:程序博客网 时间:2024/05/29 07:39
【题目】
Given a linked list and a value x,partition it such that all nodes less than x come before nodes greater than orequal to x.
You should preserve the original relativeorder of the nodes in each of the two partitions.
For example,
Given 1->4->3->2->5->2 and x= 3,
return 1->2->2->4->3->5.
给一个链表,可一个定值x,在保证链表顺序不变的前提下,将小于x的放在x前面,大于等于x的放其后。
【思路】
最简单的是创建两个头结点head1和head2;head1这条链表是小于x值的节点的链表,head2链表是大于等于x值的节点的链表,最后将head2链表链接到head链表的尾部即可。
【Python实现】
# -*- coding: utf-8 -*-
"""
Created on Wed Aug 9 16:41:48 2017
@author: Administrator
"""
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def partition(self, head, x):
"""
:type head: ListNode
:type x: int
:rtype: ListNode
"""
head1 = ListNode(0)#新的头结点,用于存放小于x的数
head2 = ListNode(0)#新的头结点,用于存放大于等于x的数
p1 = head1
p2 = head2
curr = head
while curr:
if curr.val < x:
p1.next = curr
curr = curr.next
p1 = p1.next
p1.next = None
else:
p2.next = curr
curr = curr.next
p2 = p2.next
p2.next = None
p1.next = head2.next
head = head1.next
curr = head
#打印新链表
while curr:
print(curr.val)
curr = curr.next
return head
if __name__ == '__main__':
S= Solution()
l1 = ListNode(1)
l2 = ListNode(4)
l3= ListNode(3)
l4 = ListNode(2)
l5 = ListNode(5)
l6 = ListNode(2)
head = l1
l1.next = l2
l2.next = l3
l3.next = l4
l4.next = l5
l5.next = l6
l6.next = None
S.partition(head,3)
- LeetCode 86 Partition List (Python详解及实现)
- 【LEETCODE】86- Partition List [Python]
- partition List Leetcode Python
- [Leetcode][python]Partition List
- 【LeetCode with Python】 Partition List
- LeetCode 86: Partition List
- LeetCode 86 Partition List
- [leetcode 86] Partition List
- leetcode-86 Partition List
- [LeetCode 86]Partition List
- leetcode || 86、Partition List
- LeetCode---(86) Partition List
- LeetCode 86 Partition List
- Leetcode[86]-Partition List
- leetcode[86]:Partition List
- Leetcode #86 Partition List
- LeetCode(86) Partition List
- leetcode 86: Partition List
- python实例(求数)
- 基础拾遗------泛型详解
- uva 548 Tree
- RocketMQ(三)——HelloWorld
- 18.图像用户界面入门:EasyGui
- LeetCode 86 Partition List (Python详解及实现)
- 地震中哪些机器人能参与应急救援
- 暑期 tensorflow 小练 mnist
- 百度地图点击地点显示经纬度并且转换为百度地址及添加控件
- Unity调用Android的Java方法
- js中的那些数组处理函数区别及用法总结
- [C++11]左值、右值、左值引用、右值引用小结
- 【字符串入门专题1】F
- BigDecimal 加减乘除