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

หา Node ที่ n จากท้ายของ Linked List ใน Python

หา Node ที่ n จากท้ายโดยคำนวณความยาว List ก่อน แล้วเดินจากหัวไป (length - n) ก้าว

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

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 list_length(my_list):
    my_len = 0
    curr = my_list.head
    while curr:
        curr = curr.next
        my_len = my_len + 1
    return my_len

def return_from_end(my_list, n):
    l = list_length(my_list)
    curr = my_list.head
    for i in range(l - n):
        curr = curr.next
    return curr.data

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))

n = int(input('Enter the value for n.. '))
my_result = return_from_end(my_instance, n)
print('The nth element from the end is: {}'.format(my_result))

ผลลัพธ์

Enter the elements of the linked list..45 31 20 87 4
Enter the value for n.. 2
The nth element from the end is: 87

คำอธิบาย

  • Node และ LinkedList_structure Классพื้นฐาน
  • list_length: นับจำนวน Node
  • return_from_end: เดินจากหัว (length - n) ก้าว
  • รับค่าจากผู้ใช้ สร้าง List เรียกฟังก์ชัน