class
LinkedList(
object
):
def
__init__(
self
):
self
.head
=
None
class
Node(
object
):
def
__init__(
self
, d):
self
.data
=
d
self
.
next
=
None
def
newNode(
self
, key):
return
self
.Node(key)
def
sort(
self
):
Ahead
=
self
.Node(
0
)
Dhead
=
self
.Node(
0
)
self
.splitList(Ahead, Dhead)
Ahead
=
Ahead.
next
Dhead
=
Dhead.
next
Dhead
=
self
.reverseList(Dhead)
self
.head
=
self
.mergeList(Ahead,
Dhead)
def
reverseList(
self
, Dhead):
current
=
Dhead
prev
=
None
while
current !
=
None
:
self
._next
=
current.
next
current.
next
=
prev
prev
=
current
current
=
self
._next
Dhead
=
prev
return
Dhead
def
printList(
self
):
temp
=
self
.head
while
temp !
=
None
:
print
temp.data,
temp
=
temp.
next
print
''
def
mergeList(
self
, head1, head2):
if
head1
=
=
None
:
return
head2
if
head2
=
=
None
:
return
head1
temp
=
None
if
head1.data < head2.data:
temp
=
head1
head1.
next
=
self
.mergeList(head1.
next
,
head2)
else
:
temp
=
head2
head2.
next
=
self
.mergeList(head1,
head2.
next
)
return
temp
def
splitList(
self
, Ahead, Dhead):
ascn
=
Ahead
dscn
=
Dhead
curr
=
self
.head
while
curr !
=
None
:
ascn.
next
=
curr
ascn
=
ascn.
next
curr
=
curr.
next
if
curr !
=
None
:
dscn.
next
=
curr
dscn
=
dscn.
next
curr
=
curr.
next
ascn.
next
=
None
dscn.
next
=
None
llist
=
LinkedList()
llist.head
=
llist.newNode(
10
)
llist.head.
next
=
llist.newNode(
40
)
llist.head.
next
.
next
=
llist.newNode(
53
)
llist.head.
next
.
next
.
next
=
llist.newNode(
30
)
llist.head.
next
.
next
.
next
.
next
=
llist.newNode(
67
)
llist.head.
next
.
next
.
next
.
next
.
next
=
llist.newNode(
12
)
llist.head.
next
.
next
.
next
.
next
.
next
.
next
=
llist.newNode(
89
)
print
'Given linked list'
llist.printList()
llist.sort()
print
'Sorted linked list'
llist.printList()