+91 81900 98289

Linked Lists

This Linked Lists lesson is for a beginner. Read the short notes, run each example, then change one name or number and run it again.

A linked list stores each value in a node that points at the next node. Inserting at the front does not move the other nodes.

Finding the tenth item means walking nine links. A Python list is usually the better everyday choice.

Example 1: Start here

Keep a reference to the first node. Without it you cannot find the rest.

class Node: # a template for objects def __init__(self, value, nxt=None): # runs when you create the object self.value = value # store this on the object self.nxt = nxt # store this on the object head = Node("Python", Node("SQL")) # one object print(head.nxt.value)

Example 2: Walk the values

Linked Lists starts by visiting one value at a time. Read the printed lines from top to bottom.

values = [11, 3, 11, 7] # a list; the values stay in this order for value in values: # repeat the indented lines once per value print(value)

Example 3: Keep the largest

Many data-structure lessons reduce a list to one answer. This one remembers the largest number seen so far.

values = [11, 3, 11, 7] # a list; the values stay in this order best = values[0] # the first value for value in values: # repeat the indented lines once per value if value > best: # run the indented lines only when this is true best = value # another name for the same value print(best)

Example 4: Search for a target

A search asks one yes-or-no question: is the target in the collection? Linked Lists builds on that question.

values = [3, 11, 11] # a list; the values stay in this order target = 11 # a whole number print(target in values) # in is True when the value is found
Keep a reference to the first node. Without it you cannot find the rest.
Call Now 81900 98289