요소 목록이 있다고 가정합니다. 이러한 요소는 단일 연결 목록에 저장됩니다. 우리는 또한 값 pos와 값 val이 있습니다. 연결 리스트의 인덱스 위치 앞에 val을 삽입해야 합니다.
따라서 입력이 nums =[1,5,3,6,8] pos =3 val =7과 같으면 출력은 [1,5,3,7,6,8]
이 됩니다.이 문제를 해결하기 위해 다음 단계를 따릅니다. −
-
new :=val과 같은 값을 가진 연결 리스트 노드 생성
-
pos가 0과 같으면
-
다음 항목:=list_head
-
새로 반환
-
-
임시 :=list_head
-
temp가 null이 아니고 pos가 1과 같지 않은 동안 수행
-
temp :=temp의 다음
-
위치 :=위치 - 1
-
-
새 항목의 다음 :=임시 항목의 다음 항목
-
다음 임시 항목 :=새 항목
-
list_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(']')
def solve(list_head, pos, val):
new = ListNode(val)
if pos == 0:
new.next = list_head
return new
temp = list_head
while temp and pos != 1:
temp = temp.next
pos -= 1
next = temp.next
temp.next = new
return list_head
nums = [1,5,3,6,8]
pos = 3
val = 7
list_head = make_list(nums)
list_head = solve(list_head, pos, val)
print_list(list_head) 입력
[1,5,3,6,8], 3, 7
출력
[1, 5, 3, 7, 6, 8, ]