首页 > 其他 > 详细

Partition List

时间:2015-06-10 18:36:24      阅读:235      评论:0      收藏:0      [点我收藏+]

思路:

1. 空间复杂度为 o(n) 解法. 创建两个链表, 分别记录大于 x 和小于 x 的节点, 最后合并

2. o(1) 的空间复杂度解法. 四个指针, 分别指向小于 x 部分链表的头, 尾, 指向大于 x 部分链表的头, 尾

 为了简单,我这里使用1的思路。

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    # @param {ListNode} head
    # @param {integer} x
    # @return {ListNode}
    def partition(self, head, x):
       head1=ListNode(0)
       head2=ListNode(0)
       h1flag=head1
       h2flag=head2
       while head!=None:
           if head.val<x:
               h1flag.next=head
               h1flag=h1flag.next
               head=head.next
           else:
               h2flag.next=head
               h2flag=h2flag.next
               head=head.next
       h2flag.next=None           
       h1flag.next=head2.next
       return head1.next
            
        

 

Partition List

原文:http://www.cnblogs.com/qiaozhoulin/p/4566632.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!