pythontip 100days-day9

题目

实现一个链表类,该类有头部插入、尾部添加、查找、删除、获取长度这些方法

各方法具体说明如下

insert_to_front

  • 在链表头部插入节点
  • 输入可能为None

append

  • 在链表尾部添加节点
  • 输入可能为None

find

  • 查找值为输入的节点
  • 输入可能为None

delete

  • 删除所有值为输入的节点
  • 输入可能为None

length

  • 获取链表长度

答案

解法:

#链表节点类
class Node(object):

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

#链表类
class LinkedList(object):

    def __init__(self, head=None):
        self.head = head

    def insert_to_front(self, data):
        if data is None:
            return None
        node = Node(data, self.head)
        self.head = node
        return node   

    def append(self, data):
        if data is None:
            return None
        node = Node(data)
        if self.head is None:
            self.head = node
            return node
        curr_node = self.head
        while curr_node.next is not None:
            curr_node = curr_node.next
        curr_node.next = node
        return node

    def find(self, data):
        if data is None:
            return None
        curr_node = self.head
        while curr_node is not None:
            if curr_node.data == data:
                return curr_node
            curr_node = curr_node.next
        return None 

    def delete(self, data):
        if data is None:
            return
        if self.head is None:
            return
        if self.head.data == data:
            self.head = self.head.next
            return
        prev_node = self.head
        curr_node = self.head.next
        while curr_node is not None:
            if curr_node.data == data:
                prev_node.next = curr_node.next
                return
            prev_node = curr_node
            curr_node = curr_node.next
    
        
            
    def length(self):
        curr = self.head
        counter = 0
        while curr is not None:
            counter += 1
            curr = curr.next
        return counter