สมมติว่าเรามี linked list เราต้องลบโหนดที่ N จากท้ายของลิสต์ แล้วคืน head ตัวอย่าง ลิสต์ [1,2,3,4,5,6] และ n = 3 ลิสต์ที่คืนคือ [1,2,3,5,6]
ขั้นตอนการทำงาน (Two Pointers / Fast-Slow Pointer)
- ถ้าไม่มีโหนดหลัง head ให้คืน None
front := head, back := head, counter := 0, flag := false- วนลูป
while counter <= n:- ถ้า
frontไม่มี: ตั้ง flag true, ออกจากลูป front := next of front, เพิ่ม counter
- ถ้า
- วนลูป
while front exists:front := next of frontback := next of back
- ถ้า flag false:
temp := next of backnext of back := next of tempnext of temp := None
- มิฉะนั้น
head := next of head - คืน
head
ตัวอย่างโค้ด (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(object):
def removeNthFromEnd(self, head, n):
if not head.next:
return None
front = head
back = head
counter = 0
flag = False
while counter <= n:
if not front:
flag = True
break
front = front.next
counter += 1
while front:
front = front.next
back = back.next
if not flag:
temp = back.next
back.next = temp.next
temp.next = None
else:
head = head.next
return head
head = make_list([1,2,3,4,5,6])
ob1 = Solution()
print_list(ob1.removeNthFromEnd(head, 3))
อินพุต
[1,2,3,4,5,6] 3
เอาต์พุต
[1,2,3,5,6]