从纯C背景中删除Python中的中间节点

时间:2018-10-22 10:39:11

标签: python data-structures linked-list nodes

由于它的强大功能和语法,最近我一直在使用Python。我决定从https://www.tutorialspoint.com创建一个链表,但是由于我在C中有很强的背景,并且习惯于对其进行手动内存分配,并且具有指向其中一个的指针,所以删除中间函数对我有些困惑。我知道对象会引用其他对象和变量,并且Python解释器会自动处理此问题:

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

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

    def printlist(self):
        cur = self.head
        while cur is not None:
            print(cur.data)
            cur = cur.next
    def insertAtHead(self, newdata):
        NewNode = Node(newdata) #create new node

        newNode.next = self.head #create its .next to point to the current node

        self.head = newNode #set its .next to point the current head
#creates a linked list with 3 elements
    def createOneTwoThree(self):
        list = SLinkedList()
        list.head = Node('Mon')
        e2 = Node('Tues')
        e3 = Node('Wed')

        list.head.next = e2
        e2.next = e3
#function to add at the end of a linked list
    def insertAtEnd(self, newdata):
        newNode = Node(newdata)#create new node
        if self.head = newNode:#if empty insert the thing
            self.head = newNode
            return
        laste = self.head
        while(last.next):
            last = last.next
        last.next = newNode


    def inBetween(self, middle_node,newdata):
        if middle_node is None:
            print('Error 0: The mentioned node is absent')
            return

            newNode = Node(newdata)
            newNode.next = middle_node.next
            middle_node.next = newNode
   def delete(self, removeKey):

       headVal = self.head

       if(head  is not None):
           if (head.data == removeKey):
               break
            prev = head
            head = None

        while(head is not None):
            if head.data == removeKey:
                break
            prev = head
            head = head.next

        if (head == None):
            return
        prev.next = head.next

        head = None

#Link Firt node to second node: list1.head.next = n2*******

从内存的角度来看,我只是看不到这里发生了什么,这证明它找到两个所述值之间并将它们链接在一起是合理的。我仍然对Python及其类和结构还是陌生的,但是从直观的角度来看,尽管inBetween方法是最基本的逻辑,但对我来说却毫无意义。谁能更精通Python,请向我解释为什么会发生这种情况,以及对象,引用和指针到底发生了什么?

0 个答案:

没有答案