program mengurutkan data linked list pada python

Pada kesempatan kali ini saya akan membuat program sort/mengurutkan data single linked list pada bahasa pemrograman python versi 2,7

Berikut source codenya: Bisa liat dibawah atau dari Github

print "PROGRAM MENGURUTKAN DATA SINGLE LINKED LIST"
class Node():
    def __init__(self, data):
        self.data = data
        self.next = None

class LinkedList ():
    def __init__(self):
        self.head = None

    def insert (self, new_data):
        new_node = node(new_data)
        if self.head is None:
            self.head = new_node
            return
        last = self.head
        while(last.next):
            last = last.next

        last.next = new_node

    def ShowData (self):
        current = self.head
        while current is not None:
            print current.data,
            current = current.next

    def SortList (self):
        current = self.head
        index = None

        if (self.head == None):
            return
        else:
            while (current != None):
                index = current.next

                while (index != None):
                    if (current.data > index.data):
                        temp = current.data
                        current.data = index.data
                        index.data = temp
                    index = index.next
                current = current.next

list = LinkedList()
list.insert(0)
list.insert(5)
list.insert(-4)
list.insert(-2)
list.insert(3)
print "Sebelum Diurutksn:"
list.ShowData()
print "\n"
print "Setelah Diurutkan:"
list.SortList()
list.ShowData()

Outputnya:

 

Semoga bermanfaat

Post a Comment

0 Comments