Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

หา Node กลาง (Middle Node) ของ Linked List ใน Python

หา Node กลางของ Linked List โดยนับความยาวก่อน แล้วเดินไปที่ตำแหน่ง (length-1)//2

ตัวอย่างโค้ด

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

class LinkedList_structure:
    def __init__(self):
        self.head = None
        self.last_node = None
    def add_vals(self, data):
        if self.last_node is None:
            self.head = Node(data)
            self.last_node = self.head
        else:
            self.last_node.next = Node(data)
            self.last_node = self.last_node.next

def print_middle_val(my_list):
    curr = my_list.head
    my_len = 0
    while curr:
        curr = curr.next
        my_len = my_len + 1
    curr = my_list.head
    for i in range((my_len - 1)//2):
        curr = curr.next
    if curr:
        if my_len % 2 == 0:
            print('The two middle elements are {} and {}'.format(curr.data, curr.next.data))
        else:
            print('The middle-most element is {}.'.format(curr.data))
    else:
        print('The list is empty')

my_instance = LinkedList_structure()
my_list = input('Enter the elements of the linked list... ').split()
for elem in my_list:
    my_instance.add_vals(int(elem))

print_middle_val(my_instance)

ผลลัพธ์

Enter the elements of the linked list... 56 23 78 99 34 11
The two middle elements are 78 and 99

คำอธิบาย

  • นับความยาว List (my_len)
  • เดินจากหัว (my_len-1)//2 ก้าว
  • ถ้าความยาวคู่: แสดง 2 ตัวกลาง, คี่: แสดง 1 ตัวกลาง