Sorted Linked List in Python

linked list python
bubble sort linked list python
insertion sort linked list
ordered linked list java
sort a linked list c#
ordered linked list in data structure
merge sort linked list space complexity
java sort linked list of integers

I'm having a bit of trouble figuring out how to sort a Singly Linked list in Python. I've figured out how to create a linked list and push data onto it but how do I push it in a sorted format (not sorting after all the data is pushed onto it) or just sorting it in any way?

Objective

Create a sorted singly linked list of numbers based upon user input. Program logic: Ask for a number, add that number to the list in sorted position, print the list. Repeat until they enter -1 for the number.

Current Code
#!/usr/bin/env python

class node:
    def __init__(self):
        self.data = None # contains the data
        self.next = None # contains the reference to the next node


class linked_list:
    def __init__(self):
        self.cur_node = None

    def add_node(self, data):
        new_node = node() # create a new node
        new_node.data = data
        new_node.next = self.cur_node # link the new node to the 'previous' node.
        self.cur_node = new_node #  set the current node to the new one.

    def list_print(self):
        node = self.cur_node # cant point to ll!
        while node:
            print(node.data)
            node = node.next


def main():
  ll = linked_list()

  num=int(input("Enter a num to push onto the list, -1 to stop: "))
  while num!=-1:
    data=num
    ll.add_node(data)
    num=int(input("Enter a num to push onto the list, -1 to stop: "))

  print("\n")
  ll.list_print()
main()

I'm really stuck here. Thank you in advance for any help!


This should do it:

>>> class Node:
...   def __init__(self):
...     self.data = None
...     self.next = None
... 
>>> class LinkedList:
...   def __init__(self):
...     self.head = None
...   
...   def addNode(self, data):
...     curr = self.head
...     if curr is None:
...       n = Node()
...       n.data = data
...       self.head = n
...       return
...     
...     if curr.data > data:
...       n = Node()
...       n.data = data
...       n.next = curr
...       self.head = n
...       return
...     
...     while curr.next is not None:
...       if curr.next.data > data:
...         break
...       curr = curr.next
...     n = Node()
...     n.data = data
...     n.next = curr.next
...     curr.next = n
...     return
...   
...   def __str__(self):
...     data = []
...     curr = self.head
...     while curr is not None:
...       data.append(curr.data)
...       curr = curr.next
...     return "[%s]" %(', '.join(str(i) for i in data))
...   
...   def __repr__(self):
...     return self.__str__()
... 
>>> def main():
...   ll = LinkedList()
...   num = int(input("Enter a number: "))
...   while num != -1:
...     ll.addNode(num)
...     num = int(input("Enter a number: "))
...   c = ll.head
...   while c is not None:
...     print(c.data)
...     c = c.next
... 
>>> main()
Enter a number: 5
Enter a number: 3
Enter a number: 2
Enter a number: 4
Enter a number: 1
Enter a number: -1
1
2
3
4
5

Sort a linked list that is sorted alternating ascending and descending , Merge both lists. Below are the implementations of above algorithm. C++; Java; Python; C#. C++. After traversing the linked list and finding the minimum value, we delete this node, instantiate a new node with a value equal to the selection, and insert this node at the sorted_idx. Lastly, we increment the sorted_idx by 1 and repeat until this index equals the count attribute minus 1 (because there’s no nodes available to traverse after we’ve reached the last node.)


class Node:
    def __init__(self, data):
        self.data = int(data)
        self.next = None

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

    def asc_ordered_list(self, data):
        new_node = Node(data)
        if self.head is None:
            self.head = new_node
            return

        temp = self.head
        if temp.data > data:
            new_node.next = temp
            self.head = new_node
            return

        while temp.next:
            if temp.next.data > data:
                break
            temp = temp.next

        new_node.next = temp.next
        temp.next = new_node

    def desc_ordered_list(self, data):
        new_node = Node(data)
        if self.head is None:
            self.head = new_node
            return

        temp = self.head
        if data > temp.data:
            new_node.next = temp
            self.head = new_node
            return

        while temp.next:
             if temp.data > data and temp.next.data < data:
                 break
             temp = temp.next

        new_node.next = temp.next
        temp.next = new_node

    def display_list(self):
        temp = self.head
        while temp is not None:
            print("data = {0}".format(temp.data))
            temp = temp.next

if __name__ == "__main__":
    llist = LinkedList()
    llist.desc_ordered_list(8)
    llist.desc_ordered_list(3)
    llist.desc_ordered_list(1)
    llist.desc_ordered_list(4)
    llist.desc_ordered_list(5)
    llist.desc_ordered_list(7)
    llist.desc_ordered_list(6)
    llist.desc_ordered_list(2) 
    llist.display_list()

Given a linked list which is sorted, how will you insert in sorted way , 4) Insert the node (9) after the appropriate node (7) found in step 3. Implementation: C++; C; Java; Python; C#. C++. A linked list is a sequence of data elements, which are connected together via links. Each data element contains a connection to another data element in form of a pointer. Python does not have linked lists in its standard library. We implement the concept of linked lists using the concept of nodes as discussed in the previous chapter.


I thought this was a bit shorter and easier

class Node:
    def __init__(self, data, _next=None):
        self.data = data
        self.next = _next

def main():
    nodes = []
    num = int(input("Enter number: "))
    while num != -1:
        nodes.append(Node(num))
        num = int(input("Enter number: "))

    # If list is empty then just end function
    if len(nodes) == 0: 
        return

    # Let python do the sorting
    nodes = sorted(nodes, key=lambda node: node.data)

    # Link the nodes together and print them while you're at it
    for i in range(len(nodes) - 1):
        nodes[i].next = nodes[i + 1]
        print(nodes[i].data)
    # We need to print the last node
    print(nodes[-1].data)

Sorting and Merging Single Linked List, The process continues until the list is completely sorted. The Python code for sorting the linked list using bubble sort by exchanging the data is as follows: The Python code for sorting the linked list using bubble sort by exchanging the data is as follows: def bub_sort_datachange(self): end = None while end != self.start_node: p = self.start_node while p.ref != end: q = p.ref if p.item > q.item: p.item, q.item = q.item, p.item p = p.ref end = p


Implementing the Linked List and Selection Sort in python! (from , In this post, I'm going to implement the linked list from scratch and build important functionality such as insertion (and insert_at), deletion, swap,  Using popleft(), you removed elements from the head of the linked list until you reached the Real Python home page. From the examples above, you can see how useful it can be to have collections.deque in your toolbox, so make sure to use it the next time you have a queue- or stack-based challenge to solve.


Python: Sorting a Linked List, Remember, in Python we do not have any built-in linked list. Algorithm. Let's understand the algorithm for merging two  # A python script representing linked list # A Node class. A single Node has a data and its next is NULL: class Node: def __init__ (self, data): self. data = data: self. next = None: class LinkedList: #initially an empty list so head is NULL: def __init__ (self): self. head = None: #append at the end of the list: def appendList (self, data


How to merge two sorted linked lists in Python, The search of an unordered linked list required that we traverse the nodes one at The actual implementation of a Python list is based on the notion of an array. Rearrange a given linked list in-place. Sort a linked list that is sorted alternating ascending and descending orders? Select a Random Node from a Singly Linked List; Construct a Doubly linked linked list from 2D Matrix; Find the string formed by joining k consecutive nodes of linked list; Operator Overloading '<<' and '>>' operator in a linked list class