简体   繁体   English

如何在python的单链表的中间插入数据?

[英]How do I insert data into the middle of a singlelinkedlist in python?

Node Class and SingleLinkedList Class code: 节点类和SingleLinkedList类代码:

class Node():
'''represents a node as a building block of a single linked list'''
def __init__(self, element, next_node=None):
    '''(Node, obj, Node) -> NoneType
    construct a node as building block of a single linked list'''

    self._element = element
    self._next = next_node

def set_next(self, next_node):
    '''(Node, Node) -> NoneType
    set node to point to next_node'''
    self._next = next_node

def set_element(self, element):
    '''(Node, obj) ->NoneType
    set the _element to a new value'''
    self._element = element

def get_next(self):
    '''(Node) -> Node
    returns the reference to next node'''
    return self._next

def get_element(self):
    '''(Node) -> obj
    returns the element of this node'''
    return self._element

def __str__(self):
    '''(Node) -> str
    returns the element of this node and the reference to next node'''
    return "(" + str(self._element) + ", " + str(hex(id(self._next))) + ")"

class SingleLinkedList():
''' represents a single linked list'''
def __init__(self):
    '''(SingleLinkedList) ->NoneType
    initializes the references of an empty SLL'''
    self._size = 0
    self._head = None
    self._tail = None
    self._value = None
    self._next = None
def set_head(self, new_head):
    '''(SingleLinkedList) -> None
    updates the head'''
    self._head = new_head
def set_tail(self, new_tail):
    '''(SingleLinkedList) -> None
    updates the tail'''
    self._tail = new_tail
def get_head(self):
    '''(SingleLinkedList) -> Node
    Return the pointer to the head'''
    return self._head 
def get_tail(self):
    '''(SingleLinkedList) -> Node
    Return the pointer to the tail'''
    return self._tail

def is_empty(self):
    '''(SingleLinkedList) -> bool
    returns true if no item is in this SLL'''
    return self._size == 0

def size(self):
    '''(SingleLinkedList) -> int
    returns the number of items in this SLL'''
    return self._size

def add_first(self, element):
    '''(SingleLinkedList, obj) -> NoneType
    adds a node to the first of the SLL'''
    # create a node that point to the head
    node = Node(element, self._head)
    # let head point to the node
    self._head = node
    # if this node is the first node in this SLL, tail should point to this node too
    if (self._size == 0):
        self._tail = node
    # increment the size
    self._size += 1

def add_last(self, element):
    '''(SingleLinkedList, obj) -> NoneType
    adds a node to the end of this SLL'''
    # create a node with the given element that points to None
    node = Node(element, None)
    # let the _next part of the tail to point to newly created node
    self._tail.set_next(node)
    #let tail to point to the added node
    self._tail = node
    # if this node is the first node in this SLL, let head to point to this node too
    if (self._size == 0):
        self._head = node
    # increment the size
    self._size += 1

def remove_first(self):
    '''(SingleLinkedList, obj) -> obj
    remvoe the node from the head of this SLL and returns the element stored in this node'''
    # sset element to None in case SLL was empty
    element = None
    # if SLL is not empty
    if (self._head is not None):
        # get the first node
        node = self._head
        # let head point to the second node
        self._head = self._head.get_next()
        # decrement the size
        self._size -= 1
        #set the _next of previous head to point to None (for garbage collection purpose)
        node.set_next(None)
        # get the element stored in the node
        element = node.get_element()
    #return the element of the removed node
    return element

def __str__(self):
    '''(SingleLinkedList) -> str
    returns the items in the SLL in a string form
    '''
    # define a node, which points to the head
    cur = self._head
    # define an empty string to be used as a container for the items in the SLL
    result = ""
    # loop over the SLL until you get to the end of the SLL
    while (cur is not None):
        # get the element that of the current node and attach it to the final result
        result = result + str(cur.get_element())  + ", "
        # proceed to next node
        cur = cur.get_next()
    #enclose the result in a parantheses
    result = "(" + result[:-2] + ")"
    #return the result
    return result

As you can see, there are already functions to add at the head and add at the tail, but I dont know how to add in the middle of the list. 如您所见,已经有一些函数可以添加到开头,然后添加到结尾,但是我不知道如何在列表的中间添加。 I need to make a function that takes new data, and adds a node with the data in the middle of the singlelinkedlist. 我需要制作一个接受新数据的函数,并在单链表的中间添加一个包含数据的节点。 Would someone be able to show me code or how to modify one of these functions or add a new one? 有人可以向我展示代码,或者如何修改这些功能之一或添加新功能吗? Appreciate the help! 感谢帮助!

You have to start from the first elements, then iterate through the list until you reach the position you want to insert. 您必须从第一个元素开始,然后遍历列表,直到到达要插入的位置。 Let's say you need to add a node node_to_insert to position pos : 假设您需要将一个节点node_to_insert添加到位置pos

current_node = self.get_head()
for i in range(pos): # iterate pos time:
    current_node = current_node.get_next() # Jump to next node
# Now curr node is `pos`-th node. We insert `node_to_insert` here.  
# Suppose u already have it named `node_to_insert`.  
# We need to store the next node (of current node),  
# so we can link the inserted node to it
next_current_node = current_node.get_next()
current_node.set_next(node_to_insert)
node_to_insert.set_next(next_current_node)

That's all. 就这样。 Hope this help. 希望能有所帮助。 I didn't test the code, but I hope u get my idea. 我没有测试代码,但希望您能理解。

This should work: 这应该工作:

class SingleLinkedList():

    ...

    def add_after(self, n, element):
        """add element after the n-th node, counting from 1 (if n=0, add before the first node)"""
        # check if we should add at the start...
        if (n<=0):
            self.add_first(element)
        # ... or the end
        elif (n>=self.size()):
            self.add_last(element)
        # otherwise, add after node n
        else:
            # start at the first node
            node = self.get_head()
            # loop over nodes until we reach node n
            for i in range(n - 1):
                node = node.get_next()
            # make a new node from our element
            new_node = Node(element,node.get_next())
            # insert it after node n
            node.set_next(new_node)

Testing: 测试:

# test
q = SingleLinkedList()
q.add_first('A')
q.add_last('B')
q.add_last('C')
q.add_last('D')
q.add_last('E')
q.add_after(2, 'X')

print(q) # (A, B, X, C, D, E)

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

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