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

โปรแกรมลบรายการซ้ำในลิงก์ลิสต์ใน Python

สมมติว่าเรามีลิงก์ลิสต์ของตัวเลข เราต้องลบตัวเลขที่ปรากฏหลายครั้ง (เก็บแค่ครั้งแรก) และรักษาลำดับการปรากฏเดิม

ตัวอย่าง: [2 → 4 → 6 → 1 → 4 → 6 → 9] ผลลัพธ์คือ [2 → 4 → 6 → 1 → 9]

ขั้นตอนการแก้ปัญหา

  1. ถ้า node ไม่ใช่ None:
    • สร้างเซต l ว่าง
    • temp = node
    • เพิ่ม temp.val เข้า l
    • วนลูป while temp.next ไม่ใช่ None:
      • ถ้า temp.next.val ไม่อยู่ใน l:
        • เพิ่ม temp.next.val เข้า l
        • temp = temp.next
      • อื่นๆ: temp.next = temp.next.next (ข้ามโหนดซ้ำ)
  2. คืนค่า node

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

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

def make_list(elements):
    head = ListNode(elements[0])
    for element in elements[1:]:
        ptr = head
        while ptr.next:
            ptr = ptr.next
        ptr.next = ListNode(element)
    return head

def print_list(head):
    ptr = head
    print('[', end='')
    while ptr:
        print(ptr.val, end=', ')
        ptr = ptr.next
    print(']')

class Solution:
    def solve(self, node):
        if node:
            seen = set()
            temp = node
            seen.add(temp.val)
            while temp.next:
                if temp.next.val not in seen:
                    seen.add(temp.next.val)
                    temp = temp.next
                else:
                    temp.next = temp.next.next
            return node

ob = Solution()
head = make_list([2, 4, 6, 1, 4, 6, 9])
print_list(ob.solve(head))
# Output: [2, 4, 6, 1, 9, ]

อินพุต / เอาต์พุต

Input: [2, 4, 6, 1, 4, 6, 9]

Output: [2, 4, 6, 1, 9, ]