[leetcode]Partition List @ Python
2014-06-12 09:38
295 查看
原题地址:https://oj.leetcode.com/problems/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
return
解题思路:解决链表问题时,最好加一个头结点,问题会比较好解决。对这道题来说,创建两个头结点head1和head2,head1这条链表是小于x值的节点的链表,head2链表是大于等于x值的节点的链表,然后将head2链表链接到head链表的尾部即可。
代码:
题意:
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->2and x = 3,
return
1->2->2->4->3->5.
解题思路:解决链表问题时,最好加一个头结点,问题会比较好解决。对这道题来说,创建两个头结点head1和head2,head1这条链表是小于x值的节点的链表,head2链表是大于等于x值的节点的链表,然后将head2链表链接到head链表的尾部即可。
代码:
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: # @param head, a ListNode # @param x, an integer # @return a ListNode def partition(self, head, x): head1 = ListNode(0) head2 = ListNode(0) Tmp = head phead1 = head1 phead2 = head2 while Tmp: if Tmp.val < x: phead1.next = Tmp Tmp = Tmp.next phead1 = phead1.next phead1.next = None else: phead2.next = Tmp Tmp = Tmp.next phead2 = phead2.next phead2.next = None phead1.next = head2.next head = head1.next return head
相关文章推荐
- partition List Leetcode Python
- [LeetCode]Partition List@python
- 【LeetCode with Python】 Reverse Linked List II
- leetcode:Partition List (链表处理)【面试算法题】
- LeetCode之Partition List
- [leetcode]Sort List @ Python
- Partition List -- LeetCode
- 【LeetCode with Python】 Linked List Cycle
- [leetcode]Linked List Cycle II @ Python
- Leetcode_linked-list-cycle(c++ and python version)
- Leetcode_remove-duplicates-from-sorted-list (updated c++ and python version)
- [leetcode]Reorder List @ Python
- LeetCode Partition List 按值分段链表 系统分析
- LeetCode 61 — Rotate List(C++ Java Python)
- Partition List - LeetCode
- **Leetcode_copy-list-with-random-pointer (c++ and python version)
- [Leetcode] Partition List **
- LeetCode 19 — Remove Nth Node From End of List(C++ Java Python)
- LeetCode 141 — Linked List Cycle(C++ Java Python)
- Leetcode_partition-list