Linked List

This linked list implementation shows the use of recursive functions (in this case for printing out the list) and includes a basic insertion sort.

#!/usr/bin/env python

class Link:
  def __init__(self, data, next = None): = data = next
  def __repr__(self):
    return repr((,,))

link = Link(30, Link(20, Link(25, Link(10, Link(5, Link(40))))))

def insertion_sort(top, link):
  if top is None:
    return Link(
    previous = None
    current = top
    while current and >=
      previous = current
      current =
  if previous is None:
    print "Inserting",, "at start"
    return Link(, current)
  elif current is None:
    print "Inserting",, "at end" = Link(, current)
    return top
    print "Inserting",, "between",, "and", = Link(, current)
    return top

def print_links(link, count = 0, max_count=10):
  if link:
    print "Data is",
    print_links(, count+1, max_count)

top = Link(
current =
while current:
  print top
  top = insertion_sort(top, current)
  current =

print top

Further Reading