user10715416
user10715416

Reputation:

Sorting a Linked List that contains two data in a Node

class Node :
    def __init__(self, newData=None, newArtist=None, nextNode=None):
        self.data = newData
        self.artist = newArtist
        self.next  = nextNode

    def getData(self):
        return self.data

    def setData(self, newData):
        self.data = newData

    def getArtist(self):
        return self.artist

    def setArtist(self, newArtist):
        self.artist = newArtist

    def getNext(self):
        return self.next

    def setNext(self, newNode):
        self.next = newNode

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

    def next(self, newNode, newData=None, newArtist=None):
        self.head = newNode
        self.data = newData
        self.artist = newArtist

    def printAll(self):
        i = 1
        if self.head:
            node = self.head
            if node.data:
                print('1: {} - {}'.format(node.getData(), node.getArtist()))
                i += 1
            while node.getNext():
                node = node.getNext()
                if node.data:
                    print('{}: {} - {}'.format(i, node.getData(), node.getArtist()))
                    i += 1

Song1 = Node("Silent Night", "John")
Song2 = Node("Last Christmas", "Andy")
Song3 = Node("Jingle Bells", "Mary")
Song4 = Node("Joy to the World", "Brad")

music_collection = LinkedList()
music_collection.next(Song1)
Song1.setNext(Song2)
Song2.setNext(Song3)
Song3.setNext(Song4)
music_collection.printAll()

Instead, now I would like to know if the artist's name could be sorted in descending order. Please feel free to add in other methods that can help with my understanding. (eg. deleteNode, insertNode etc)

Current output:

1: Silent Night - John
2: Last Christmas - Andy
3: Jingle Bells - Mary
4: Joy to the World - Brad

Output sorted by artist's name in descending order:

1: Jingle Bells - Mary
2: Silent Night - John
3: Joy to the World - Brad
4: Last Christmas - Andy

Upvotes: 0

Views: 119

Answers (2)

Alderven
Alderven

Reputation: 8260

Solution 1: Your solution

I've added delete method to the Node class and also added index to the printAll method:

class Node:
    def __init__(self, newData=None, newArtist=None, nextNode=None):
        self.data = newData
        self.artist = newArtist
        self.next = nextNode

    def getData(self):
        return self.data

    def setData(self, newData):
        self.data = newData

    def getArtist(self):
        return self.artist

    def setArtist(self, newArtist):
        self.artist = newArtist

    def getNext(self):
        return self.next

    def setNext(self, newNode):
        self.next = newNode

    def delete(self):
        self.data = None
        self.artist = None

    def __str__(self):
        return "%s (%s)" % (self.data, self.artist)


class LinkedList:
    def __init__(self, newData=None, newArtist=None):
        self.head = None
        self.data = newData
        self.artist = newArtist

    def next(self, newNode, newData=None, newArtist=None):
        self.head = newNode
        self.data = newData
        self.artist = newArtist

    def delete(self, node):
        if self.head:
            n = self.head
            if n == node:
                n.delete()
                return
            while n.getNext():
                n = n.getNext()
                if n == node:
                    n.delete()
                    return

    def printAll(self):
        i = 1
        if self.head:
            node = self.head
            if node.data:
                print('1: {} - {}'.format(node.getData(), node.getArtist()))
                i += 1
            while node.getNext():
                node = node.getNext()
                if node.data:
                    print('{}: {} - {}'.format(i, node.getData(), node.getArtist()))
                    i += 1


Song1 = Node("Silent Night", "John")
Song2 = Node("Last Christmas", "Andy")
Song3 = Node("Jingle Bells", "Mary")

music_collection = LinkedList()
music_collection.next(Song1)
Song1.setNext(Song2)
Song2.setNext(Song3)
music_collection.printAll()

music_collection.delete(Song3)
music_collection.printAll()

So I've got following on the output:

1: Silent Night - John
2: Last Christmas - Andy
3: Jingle Bells - Mary

When remove last song:

1: Silent Night - John
2: Last Christmas - Andy

Solution 2: More simple solution:

Just an example take a look at this:

import operator

class Node(object):
    def __init__(self, name, artist):
        self.name = name
        self.artist = artist


class LinkedList(object):
    def __init__(self):
        self.list = []

    def set_next(self, node):
        self.list.append(node)

    def print(self):
        for i, node in enumerate(self.list):
            print('{}: {} - {}'.format(i+1, node.name, node.artist))

    def delete(self, node):
        self.list.remove(node)

    def sort(self, sort_by, descending=False):
        self.list.sort(key=operator.attrgetter(sort_by), reverse=descending)


Song1 = Node("Silent Night", "John")
Song2 = Node("Last Christmas", "Andy")
Song3 = Node("Jingle Bells", "Mary")
music_collection = LinkedList()
music_collection.set_next(Song1)
music_collection.set_next(Song2)
music_collection.set_next(Song3)

music_collection.sort('artist', descending=True)
music_collection.print()

I've got on output:

1: Jingle Bells - Mary
2: Silent Night - John
3: Last Christmas - Andy

Upvotes: 0

DocDriven
DocDriven

Reputation: 3974

Overall, I think your implementation is quite complicated. For example, I do not see why it is necessary to call the LinkedList's __init__ method with any params. Also, I would recommend you rename the next function, as it might get confused with the function of the same name of the iterator protocol. You might wanna do some research on more elegant solutions.

That being said, try this piece of code as your printAll function:

def printAll(self):
    pointer = self.head
    idx = 1

    while pointer is not None:
        print(f'{idx}: {pointer.data} - {pointer.artist}')
        pointer = pointer.next
        idx += 1

Upvotes: 1

Related Questions