연결 목록이 있다고 가정하고 이를 반대로 해야 합니다. 따라서 목록이 2 -> 4 -> 6 -> 8과 같으면 새로운 역순 목록은 8 -> 6 -> 4 -> 2가 됩니다.
이 문제를 해결하기 위해 우리는 이 접근 방식을 따를 것입니다 -
- solve(head, back)와 같은 재귀적 방식으로 목록 반전을 수행하는 하나의 프로시저 정의
- 머리가 없으면 머리를 반환
- temp :=head.next
- head.next :=뒤로
- 뒤:=머리
- temp가 비어 있으면 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 reverseList(self, head):
return self.solve(head,None)
def solve(self, head, back):
if not head:
return head
temp= head.next
head.next = back
back = head
if not temp:
return head
head = temp
return self.solve(head,back)
list1 = make_list([5,8,9,6,4,7,8,1])
ob1 = Solution()
list2 = ob1.reverseList(list1)
print_list(list2) 입력
[5,8,9,6,4,7,8,1]
출력
[2, 1, 4, 3, 6, 5, 8, 7, 10, 9, 12, 11, 14, 13,]