단일 연결 목록이 있다고 가정하고 마지막 노드, 첫 번째 노드, 두 번째 마지막 노드, 두 번째 노드 등을 취하도록 재정렬해야 합니다.
따라서 입력이 [1,2,3,4,5,6,7,8,9]와 같으면 출력은 [9, 1, 8, 2, 7, 3, 6, 4, 5 , ]
이 문제를 해결하기 위해 다음 단계를 따릅니다.
-
c :=노드
-
l :=새 목록
-
c가 null이 아닌 동안 수행
-
l
끝에 c 값 삽입 -
c :=c
의 다음 -
c :=노드
-
c가 null이 아니고 l이 비어 있지 않은 동안 do
-
c의 값 :=l의 마지막 요소의 값 및 삭제
-
c :=c
의 다음 -
c가 null이면
-
루프에서 나오다
-
-
c의 값 :=l의 마지막 요소의 값 및 삭제
-
c :=c
의 다음
-
-
-
반환 노드
더 나은 이해를 위해 다음 구현을 살펴보겠습니다.
예시
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):
c = node
l = []
while c:
l.append(c.val)
c = c.next
c = node
while c and l:
c.val = l.pop()
c = c.next
if c == None:
break
c.val = l.pop(0)
c = c.next
return node
ob = Solution()
head = make_list([1,2,3,4,5,6,7,8,9])
print_list(ob.solve(head)) 입력
[1,2,3,4,5,6,7,8,9]
출력
[9, 1, 8, 2, 7, 3, 6, 4, 5, ]