📌  相关文章
📜  删除循环链表的所有偶数节点(1)

📅  最后修改于: 2023-12-03 15:07:15.077000             🧑  作者: Mango

删除循环链表的所有偶数节点

在循环链表中,每个节点都连接着下一个节点,而最后一个节点连接着第一个节点,形成一个环形的链表结构。要删除循环链表中所有偶数节点,需要遍历整个链表并删除符合条件的节点。下面是一个实现的例子:

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

class CircularLinkedList:
    def __init__(self):
        self.head = None
        self.tail = None
        self.size = 0

    # 在链表末尾添加一个节点
    def append(self, data):
        node = Node(data)
        if self.head is None:
            self.head = node
            self.tail = node
            self.tail.next = self.head
        else:
            self.tail.next = node
            self.tail = node
            self.tail.next = self.head
        self.size += 1

    # 删除所有偶数节点
    def delete_even_nodes(self):
        current = self.head
        prev = self.tail

        # 判断起始节点是否为偶数节点
        if current is not None and current.data % 2 == 0:
            self.head = current.next
            prev.next = self.head
            current = None
            return

        # 寻找偶数节点并删除
        while current.next != self.head:
            if current.data % 2 == 0:
                prev.next = current.next
                current = None
                self.size -= 1
                current = prev.next
            else:
                prev = current
                current = current.next

        # 判断最后一个结点是否为偶数结点
        if current.data % 2 == 0:
            prev.next = self.head
            self.tail = prev
            current = None
            self.size -= 1

    # 输出链表元素
    def print_list(self):
        current = self.head
        if current is None:
            print("The list is empty")
            return
        print("Circular Linked List elements are : ")
        print(current.data, end=' ')
        current = current.next
        while current != self.head:
            print(current.data, end=' ')
            current = current.next

# 示例
clist = CircularLinkedList()
clist.append(1)
clist.append(2)
clist.append(3)
clist.append(4)
clist.append(5)
clist.delete_even_nodes()
clist.print_list()

这段代码实现了往循环链表中添加节点、删除偶数节点并输出链表元素的功能。在删除偶数节点的过程中,需要特别处理起始节点和最后一个节点。运行以上代码,输出结果为:

Circular Linked List elements are : 
1 3 5 

说明成功删除了所有偶数节点。