|
| 1 | +# Copyright (c) Dec 22, 2014 CareerMonk Publications and others. |
| 2 | + |
| 3 | +# Creation Date : 2014-01-10 06:15:46 |
| 4 | +# Last modification : 2008-10-31 |
| 5 | +# by : Narasimha Karumanchi |
| 6 | +# Book Title : Data Structures And Algorithms Made In Java |
| 7 | +# Warranty : This software is provided "as is" without any |
| 8 | +# warranty; without even the implied warranty of |
| 9 | +# merchantability or fitness for a particular purpose. |
| 10 | + |
| 11 | +# Node of a Singly Linked List |
| 12 | +class Node: |
| 13 | + def __init__(self, data): |
| 14 | + self.data = data |
| 15 | + self.next = None |
| 16 | + |
| 17 | +# class for defining a linked list |
| 18 | +class PartitionList(object): |
| 19 | + # initializing a list |
| 20 | + def __init__(self): |
| 21 | + self.length = 0 |
| 22 | + self.head = None |
| 23 | + def partition(self, head, X): |
| 24 | + # lesser and greater are the two pointers used to create two list |
| 25 | + # lesser_head and greater_head are used to save the heads of the two lists. |
| 26 | + # All of these are initialized with the dummy nodes created. |
| 27 | + lesser = lesser_head = Node(0) |
| 28 | + greater = greater_head = Node(0) |
| 29 | + |
| 30 | + while head: |
| 31 | + # If the original list node is lesser than the given X, assign it to the lesser list. |
| 32 | + if head.data < X: |
| 33 | + lesser.next = head |
| 34 | + lesser = lesser.next |
| 35 | + else: |
| 36 | + # If the original list node is greater or equal to the given X, assign it to the greater list. |
| 37 | + greater.next = head |
| 38 | + greater = greater.next |
| 39 | + |
| 40 | + # move ahead in the original list |
| 41 | + head = head.next |
| 42 | + |
| 43 | + # Last node of "greater" list would also be ending node of the reformed list |
| 44 | + greater.next = None |
| 45 | + |
| 46 | + # Once all the nodes are correctly assigned to the two lists, |
| 47 | + # combine them to form a single list which would be returned. |
| 48 | + lesser.next = greater_head.next |
| 49 | + |
| 50 | + return lesser_head.next |
0 commit comments