Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Here is some list functions based on <a href="https://stackoverflow.com/questions/280243/python-linked-list#280284">Martin v. Löwis's representation</a>:</p> <pre><code>cons = lambda el, lst: (el, lst) mklist = lambda *args: reduce(lambda lst, el: cons(el, lst), reversed(args), None) car = lambda lst: lst[0] if lst else lst cdr = lambda lst: lst[1] if lst else lst nth = lambda n, lst: nth(n-1, cdr(lst)) if n &gt; 0 else car(lst) length = lambda lst, count=0: length(cdr(lst), count+1) if lst else count begin = lambda *args: args[-1] display = lambda lst: begin(w("%s " % car(lst)), display(cdr(lst))) if lst else w("nil\n") </code></pre> <p>where <code>w = sys.stdout.write</code></p> <p>Although doubly linked lists are famously used in Raymond Hettinger's <a href="http://code.activestate.com/recipes/576694-orderedset/" rel="noreferrer">ordered set recipe</a>, singly linked lists have no practical value in Python.</p> <p>I've <em>never</em> used a singly linked list in Python for any problem except educational. </p> <p>Thomas Watnedal <a href="https://stackoverflow.com/questions/280243/python-linked-list#280280">suggested</a> a good educational resource <a href="http://greenteapress.com/thinkpython/html/chap17.html" rel="noreferrer">How to Think Like a Computer Scientist, Chapter 17: Linked lists</a>:</p> <p>A linked list is either: </p> <ul> <li>the empty list, represented by None, or </li> <li><p>a node that contains a cargo object and a reference to a linked list.</p> <pre><code>class Node: def __init__(self, cargo=None, next=None): self.car = cargo self.cdr = next def __str__(self): return str(self.car) def display(lst): if lst: w("%s " % lst) display(lst.cdr) else: w("nil\n") </code></pre></li> </ul>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload