연결된 목록이 있다고 가정합니다. 목록의 끝에서 N번째 노드를 제거한 다음 헤드를 반환해야 합니다. 따라서 목록이 [1, 2, 3, 4, 5, 6]이고 n =3인 경우 반환되는 목록은 [1, 2, 3, 5, 6]이 됩니다.
이 문제를 해결하기 위해 다음 단계를 따릅니다. −
- head 다음에 노드가 없으면 None을 반환합니다.
- 앞:=머리, 뒤:=머리, 카운터:=0 및 분수:=거짓
- 동안 카운터 <=n
- front가 없으면 플래그를 true로 설정하고 루프에서 나옵니다.
- front :=전면의 다음, 카운터를 1 증가
- 프론트가 있는 동안
- 앞:=앞의 다음
- 뒤:=뒤의 다음
- 플래그가 거짓이면
- temp :=뒤의 다음
- 뒤의 다음:=임시의 다음
- 다음 임시:=없음
- 그렇지 않으면 head :=head의 다음
- 리턴 헤드
예제(파이썬)
더 나은 이해를 위해 다음 구현을 살펴보겠습니다. −
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]