단일 연결 목록이 있다고 가정하고 모든 홀수 노드와 짝수 노드를 그룹화해야 합니다. 여기서 우리는 노드의 값이 아니라 노드 위치에 대해 이야기하고 있습니다. 우리는 그 자리에서 그것을 하려고 노력해야 합니다. 따라서 노드가 [1,22,13,14,25]이면 결과는 [1,13,25,22,14]
가 됩니다.이 문제를 해결하기 위해 다음 단계를 따릅니다. −
- head가 null이거나 head의 다음이 null이면 head를 반환합니다.
- head1 :=머리, head2 :=머리 옆, head_beg :=머리 옆
- head2의 다음이 null이 아니고 다음(head의 다음이 null이 아님)인 동안
- head1 옆 :=head2 옆
- head2의 다음 =(머리의 다음)
- head1 :=head1 옆, head2 :=head2 옆
- head2의 다음이 null이 아닌 경우
- head1 옆 :=head2 옆
- head1 :=head1의 다음
- head1의 다음:=head2_beg 및 head2의 다음 =null
- 리턴 헤드
이해를 돕기 위해 다음 구현을 살펴보겠습니다. −
예시
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 oddEvenList(self, head):
if head == None or head.next ==None:
return head
head1=head
head2,head2_beg= head.next,head.next
while head2.next!= None and head2.next.next!= None:
head1.next = head2.next
head2.next = head2.next.next
head1 = head1.next
head2 = head2.next
if head2.next!=None:
head1.next = head2.next
head1 = head1.next
head1.next = head2_beg
head2.next = None
return head
ob1 = Solution()
head = make_list([1,22,13,14,25])
print_list(ob1.oddEvenList(head)) 입력
[1,22,13,14,25]
출력
[1, 13, 25, 22, 14, ]