Partition List

https://leetcode.com/problems/partition-list/

Partition List

Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.

You should preserve the original relative order 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,并保持链表的原有顺序

 1 # Definition for singly-linked list.
 2 #class ListNode:
 3     #def __init__(self, x):
 4         #self.val = x
 5         #self.next = None
 6 class Solution:
 7     # @param {ListNode} head
 8     # @param {integer} x
 9     # @return {ListNode}
10     def partition(self, head, x):
11         head1=ListNode(0)
12         head2=ListNode(0)
13         p1=head1                 #用p1,p2表示两个链表上的指针移动
14         p2=head2
15         tmp=head                 #tmp表示一直链表的指针移动
16         while tmp:
17             if tmp.val<x:
18                 p1.next=tmp
19                 tmp=tmp.next
20                 p1=p1.next
21                 p1.next=None
22                 #tmp=tmp.next
23             else:
24                 p2.next=tmp
25                 tmp=tmp.next
26                 p2=p2.next
27                 p2.next=None
28                 #tmp=tmp.next
29         p1.next=head2.next      #注意是p1.next=head2.next
30         head=head1.next
31         return head

在参考完别人代码,自己编写的过程中发现如果把tmp=tmp.next写在绿色注释的位置,结果会出错。

因为在p1.next=tmp;p1=p1.next;后p1.next=none时,也使得tmp.next=none,此时tmp=tmp.next为none,导致跳出了while tmp循环。

如: tmp=ListNode(0)
     tmp1=ListNode(1)
     tmp.next=tmp1
     a=tmp
     a.next=None

此时tmp.next就不是tmp1了,而也是None.

     a=[1,2,3]
     b=a
     b=[1,2]

此时a=[1,2], a,b是一个对象.

     a=1
     b=a
     b=2

此时a=1

类型有mutable和immutable之分,immutable类型的变量是不能改变的

基础类型,整数,元组等是immutable的

 

list,dict,对象等是mutable类型

感谢赵包子这只小黄鸭给我答疑解惑。^_^

 

posted @ 2015-06-29 19:26  小榛子  阅读(123)  评论(0编辑  收藏  举报