简体   繁体   English

从单链表到双链表

[英]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?如何编写像“next(lst)”这样的函数来返回 PREVIOUS 值而不是 NEXT 值?

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在类似于['a','b','c']的链表中, next(lst)将返回'a' ,下一次返回'b' ,下一次返回'c' ,下次它会返回错误

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 ).您将需要在每个列表项( 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:在常规双向链表中,您将向 Node 类添加一个prev属性(指向前一个节点)并添加一个 prev 方法,该方法执行如下操作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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