Python 中循环链表的帮助

发布于 2024-10-26 11:31:42 字数 2520 浏览 1 评论 0原文

我正在尝试制作一个循环单链表。我希望能够修改我的代码以获得单一喜欢的列表,但我遇到了一些麻烦。

对于我的链接列表,我有:

class Link (object):
  def __init__ (self, data, next = None):
    self.data = data
    self.next = next


class LinkedList(object):
  def __init__(self):
    self.first = None

  def __str__(self):
    a = "["
    current = self.first
    while current != None:
      a += str(current.data) + ', ' 
      current = current.next
    a = a[:-2] + ']'  
    return a  

  def __iter__(self):
    current = self.first
    a = []
    while current != None:
      a += [current.data]
      current = current.next
    return iter(a)

  def __len__ (self):
    current = self.first
    a = []
    while current != None:
      a += [current.data]
      current = current.next
    return len(a)

  def InsertFirst(self, item):
    NewLink = Link(item, self.first)
    self.first = NewLink

  def InsertLast(self, item):
    NewLink = Link(item)
    current = self.first

    if current == None:
      self.first = NewLink  
      return 

    while current.next != None:
      current = current.next
    current.next = NewLink 

  def Search(self, item):
    count = 0
    current = self.first
    while current != None:
      count += 1
      if current.data == item:
        return count
      else:
        pass
        current = current.next
    return -1

  def Delete(self, item):
    current = self.first
    previous = self.first

    if (current == None):
      return None

    while (current.data != item):
      if (current.next == None):
        return None
      else:
        previous = current
        current = current.next

    if (current == self.first):
      self.first = self.first.next
    else:
      previous.next = current.next

    return current

到目前为止,对于我的循环列表,我有:

class Link (object):
  def __init__ (self, data, next = None):
    self.data = data
    self.next = next


class CircularList(object):
  def __init__(self):
    self.first = Link(None, None)
    self.head = Link(None, self.first)

  def __str__(self):
    a = "["
    current = self.first
    while current != None:
      a += str(current.data) + ', ' 
      current = current.next
    a = a[:-2] + ']'  
    return a  

  def InsertLast(self, item):
    NewLink = Link(item)
    current = self.first

    if current == None:
      self.first = NewLink  
      return 

    while current.next != None:
      current = current.next
    current.next = Link(item)

我的问题是如何将最后一个元素链接回第一个元素,以便我可以横向?

I'm trying to make a circular singly linked list. I'd like to be able to modify my code for a singly liked list but I'm have some trouble.

For my linked list I have:

class Link (object):
  def __init__ (self, data, next = None):
    self.data = data
    self.next = next


class LinkedList(object):
  def __init__(self):
    self.first = None

  def __str__(self):
    a = "["
    current = self.first
    while current != None:
      a += str(current.data) + ', ' 
      current = current.next
    a = a[:-2] + ']'  
    return a  

  def __iter__(self):
    current = self.first
    a = []
    while current != None:
      a += [current.data]
      current = current.next
    return iter(a)

  def __len__ (self):
    current = self.first
    a = []
    while current != None:
      a += [current.data]
      current = current.next
    return len(a)

  def InsertFirst(self, item):
    NewLink = Link(item, self.first)
    self.first = NewLink

  def InsertLast(self, item):
    NewLink = Link(item)
    current = self.first

    if current == None:
      self.first = NewLink  
      return 

    while current.next != None:
      current = current.next
    current.next = NewLink 

  def Search(self, item):
    count = 0
    current = self.first
    while current != None:
      count += 1
      if current.data == item:
        return count
      else:
        pass
        current = current.next
    return -1

  def Delete(self, item):
    current = self.first
    previous = self.first

    if (current == None):
      return None

    while (current.data != item):
      if (current.next == None):
        return None
      else:
        previous = current
        current = current.next

    if (current == self.first):
      self.first = self.first.next
    else:
      previous.next = current.next

    return current

So far for my circular list I have:

class Link (object):
  def __init__ (self, data, next = None):
    self.data = data
    self.next = next


class CircularList(object):
  def __init__(self):
    self.first = Link(None, None)
    self.head = Link(None, self.first)

  def __str__(self):
    a = "["
    current = self.first
    while current != None:
      a += str(current.data) + ', ' 
      current = current.next
    a = a[:-2] + ']'  
    return a  

  def InsertLast(self, item):
    NewLink = Link(item)
    current = self.first

    if current == None:
      self.first = NewLink  
      return 

    while current.next != None:
      current = current.next
    current.next = Link(item)

My question is how do I link the last element back to the first so I can transverse?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

陌若浮生 2024-11-02 11:31:43

Node 类将创建一个空节点,插入函数将通过调用 Node 类创建一个节点。然后我们检查头节点,如果为空,则创建新节点作为头节点。否则搜索节点指针为 Null 并插入新节点。

class clinkedlist:
  def __init__(self):
    self.head = None

  def insertat(self,data):
    new_node = Node(data)

    if self.head is None:
        self.head = new_node
    else:
        new_node.next = self.head
        self.head = new_node
  def traverse(self):
    printval = self.head
    print(printval.data)
    
    while (True):
        printval = printval.next
        print(printval.data)
        if printval == self.head:
            break


    print(printval)

The class Node will create an empty node and the insert function will create a node by calling Node class. Then we check for the head node and in case empty , create the new node as head node.else search for the node pointer to be Null and insert the new node.

class clinkedlist:
  def __init__(self):
    self.head = None

  def insertat(self,data):
    new_node = Node(data)

    if self.head is None:
        self.head = new_node
    else:
        new_node.next = self.head
        self.head = new_node
  def traverse(self):
    printval = self.head
    print(printval.data)
    
    while (True):
        printval = printval.next
        print(printval.data)
        if printval == self.head:
            break


    print(printval)
清醇 2024-11-02 11:31:42

循环链表的要点是跳过所有“如果下一个不是 None”逻辑。一开始,头指向自身,表明链表为空。不需要创建一个空的“第一个” - 在开始时 do:

self.head = Link(None, None)
self.head.next = self.head

然后要在其他节点之后插入一个节点,只需执行以下操作:

def insert_after(insert_node, after_node):
    insert_node.next = after_node.next
    after_node.next = insert_node

要在列表的开头插入,请执行:

insert_after(node, head)

Insert before 需要迭代来查找“before”节点,因为列表只是单向链接:

def insert_before(node, before_node):
    loc = head
    while loc.next is not before_node:
        loc = loc.next
    insert_after(insert_node, loc)

要在列表末尾插入,请执行以下操作:

insert_before(node, head)

要获取列表的所有元素,请执行:

current = self.head.next
while current is not self.head:
    # do something with current.data

    # advance to next element
    current = current.next

但循环列表中的真正功能是使其成为双向链接,因此您可以插入之前而不迭代。

The point of a circular linked list is to skip all of the "if next is not None" logic. At the beginning, the head points to itself, indicating that the list is empty. There is no need to create an empty "first" - at the very start do:

self.head = Link(None, None)
self.head.next = self.head

Then to insert a node after some other node, you just do:

def insert_after(insert_node, after_node):
    insert_node.next = after_node.next
    after_node.next = insert_node

To insert at the beginning of the list, do:

insert_after(node, head)

Insert before requires iterating to find the "before" node, since the list is only singly linked:

def insert_before(node, before_node):
    loc = head
    while loc.next is not before_node:
        loc = loc.next
    insert_after(insert_node, loc)

To insert at the end of the list, do:

insert_before(node, head)

To get all elements of the list do:

current = self.head.next
while current is not self.head:
    # do something with current.data

    # advance to next element
    current = current.next

But the real power in a circular list is to make it doubly linked, so you can insert before without iterating.

浪推晚风 2024-11-02 11:31:42

last.next = 第一个创建时?

class Link (object):
  def __init__ (self, data, next = None):
    self.data = data
    self.next = self.first

可能不是有效的代码。但既然你在创建时保证位于列表的最后一部分,那么你也可以。

last.next = first when created?

class Link (object):
  def __init__ (self, data, next = None):
    self.data = data
    self.next = self.first

Might not be valid code. But since you're guaranteed to be at the last part of the list when creating then you might as well.

找回味觉 2024-11-02 11:31:42
class cirlist(list):
    def __init__(self,*arg):
        super(cirlist,self).__init__(*arg)
        self.m=super(cirlist,self).__getitem__(0)
        self.Index=0
    def next(self):
        if self.Index>=super(cirlist,self).__len__()-1:
            self.m=super(cirlist,self).__getitem__(0)
        else:
            self.m=super(cirlist,self).__getitem__(self.Index+1)
        if self.Index>super(cirlist,self).__len__()-1:    
            self.Index=super(cirlist,self).index(self.m)+1
        else:
            self.Index=super(cirlist,self).index(self.m)
        return self.m
class cirlist(list):
    def __init__(self,*arg):
        super(cirlist,self).__init__(*arg)
        self.m=super(cirlist,self).__getitem__(0)
        self.Index=0
    def next(self):
        if self.Index>=super(cirlist,self).__len__()-1:
            self.m=super(cirlist,self).__getitem__(0)
        else:
            self.m=super(cirlist,self).__getitem__(self.Index+1)
        if self.Index>super(cirlist,self).__len__()-1:    
            self.Index=super(cirlist,self).index(self.m)+1
        else:
            self.Index=super(cirlist,self).index(self.m)
        return self.m
花想c 2024-11-02 11:31:42
class Link (object):

def __init__(self, first=None, rest=None):
    self.first = first
    self.rest = rest
def get_data(self):
    return self.first
def get_next(self):
    return self.rest
def __getitem__(self, i):
    if i ==  0:
        return self.first
    get = self
    while i > 0:
        get = get.rest
        i -= 1
    if get == None:
        raise IndexError('The Sentence Index is Out of Range.')
    return get.first

class Circular_Link(对象):

def __init__(self, things):
    assert len(things) > 2
    last = Link(things[len(things)-1])
    first = Link(things[len(things)-2], last)
    index = len(things)-2
    while index > 0:
        index -= 1
        first = Link(things[index], first)
    last.rest = first
    self.circle = first
def __getitem__(self, i):
    return self.circle[i]

此示例从普通列表初始化循环列表。

class Link (object):

def __init__(self, first=None, rest=None):
    self.first = first
    self.rest = rest
def get_data(self):
    return self.first
def get_next(self):
    return self.rest
def __getitem__(self, i):
    if i ==  0:
        return self.first
    get = self
    while i > 0:
        get = get.rest
        i -= 1
    if get == None:
        raise IndexError('The Sentence Index is Out of Range.')
    return get.first

class Circular_Link (object):

def __init__(self, things):
    assert len(things) > 2
    last = Link(things[len(things)-1])
    first = Link(things[len(things)-2], last)
    index = len(things)-2
    while index > 0:
        index -= 1
        first = Link(things[index], first)
    last.rest = first
    self.circle = first
def __getitem__(self, i):
    return self.circle[i]

This example initializes the circular list from a normal list.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文