简体   繁体   中英

From single linked list to double linked list

How can I write a function like 'next(lst)' that returns the PREVIOUS value instead of the NEXT value?

class EmptyNode():
    __slots__ = ()

class Node():
    __slots__ = ('data', 'next')


class MyList():
"""A class that encapsulates a node based linked list"""
    __slots__ = ('head', 'size', 'cursor')

def mkEmptyNode():
    return EmptyNode()

def mkNode(data, next):
    node = Node()
    node.data = data
    node.next = next
    return node

def mkMyList():
    lst = MyList()
    lst.head = mkEmptyNode()
    lst.size = 0
    lst.cursor = mkEmptyNode()
    return lst

In a linked list similar to ['a','b','c'] , next(lst) will return 'a' , the next time it will return 'b' , the next time it will return 'c' , and the next time it will return an error

def next(lst):
    if isinstance(lst.cursor, EmptyNode):
        raise IndexError("cursor is invalid")

    val = lst.cursor.data
    lst.cursor = lst.cursor.next
    return val

You will need to maintain an additional pointer in each list item ( previous ).

class EmptyNode():
  __slots__ = ()

class Node():
  __slots__ = ('data', 'next', 'prev')

class MyList():
  """A class that encapsulates a node based linked list"""
  __slots__ = ('head', 'size', 'cursor')

def mkEmptyNode():
  return EmptyNode()

def mkNode(prev, data, next):
  node = Node()
  node.prev = prev
  node.data = data
  node.next = next
  return node

def mkMyList():
  lst = MyList()
  lst.head = mkEmptyNode()
  lst.size = 0
  lst.cursor = mkEmptyNode()
  return lst

You can then use it to navigate the list backwards:

def previous(lst):
  if isinstance(lst.cursor, EmptyNode):
    raise IndexError("cursor is invalid")

  val = lst.cursor.data
  lst.cursor = lst.cursor.prev
  return val

In a regular doubly linked list, you'd add a prev attribute to the Node class (pointing to the previous node) and add a prev method that does something like:

class Node():
    __slots__ = ('data', 'next', 'prev')

and then:

def prev(lst):
    if isinstance(lst.cursor, EmptyNode):
        raise IndexError("cursor is invalid")

    val = lst.cursor.data
    lst.cursor = lst.cursor.prev
    return val

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM