단일 연결 목록이 회문인지 확인하려고합니다. 제약은-알고리즘이 선형 시간과 일정한 공간에 있어야합니다.
내가 사용하는 기본 알고리즘은 다음과 같습니다.
내 구현은 목록에 요소 수가 짝수 일 때 작동하지만 요소 수가 홀수이면 실패합니다.
/*
* @brief Checks if a list is a palindrome or not
*/
bool is_palindrome(node *head)
{
node *first; /* Points to head node of 1st half */
node *second; /* Points to head node of 2nd half */
node *f_ptr = head; /* Fast pointer */
node *s_ptr = head; /* Slow pointer */
node *prev = NULL; /* Previous to slow pointer */
bool ret = false; /* Return value */
while (f_ptr && f_ptr->next && f_ptr->next->next)
{
prev = s_ptr;
s_ptr = s_ptr->next;
f_ptr = f_ptr->next->next;
}
/* List with even number of elements */
if (!(f_ptr->next->next))
{
first = head;
second = s_ptr->next;
s_ptr->next = NULL;
/* Reverse the second half */
second = reverse_list(&second);
/* Compare the first & second half */
ret = are_identical(first, second);
/* Finally, construct the original list back */
second = reverse_list(&second);
s_ptr->next = second;
print_list(head);
}
/* List with odd number of elements */
if (!(f_ptr->next))
{
first = head;
second = s_ptr->next;
prev->next = NULL;
s_ptr->next = NULL;
/* Reverse the second half */
second = reverse_list(&second);
/* Compare the first & second half */
ret = are_identical(first, second);
/* Finally, construct the original list back */
second = reverse_list(&second);
prev->next = s_ptr; s_ptr->next = second;
print_list(head);
}
return ret;
}
누군가가 홀수 사건을 처리하는 동안 내가 뭘 잘못하고 있는지 알아낼 수 있습니까? 이 프로그램의 전체 구현은 여기 에서 찾을 수 있습니다 .
버그를 지적 해 주신 s7amuser 에게 감사드립니다 . 다음은 짝수 및 홀수 경우 모두에서 작동하는 구현입니다.
/*
* @brief Checks if a list is a palindrome or not
*/
bool is_palindrome(node *head)
{
node *first; /* Points to head node of 1st half */
node *second; /* Points to head node of 2nd half */
node *f_ptr = head; /* Fast pointer */
node *s_ptr = head; /* Slow pointer */
node *prev = NULL; /* Previous to slow pointer */
bool ret = false; /* Return value */
while (f_ptr && f_ptr->next && f_ptr->next->next)
{
prev = s_ptr;
s_ptr = s_ptr->next;
f_ptr = f_ptr->next->next;
}
/* List with odd number of elements */
if (!(f_ptr->next))
{
first = head;
second = s_ptr->next;
prev->next = NULL;
s_ptr->next = NULL;
/* Reverse the second half */
second = reverse_list(&second);
/* Compare the first & second half */
ret = are_identical(first, second);
/* Finally, construct the original list back */
second = reverse_list(&second);
prev->next = s_ptr; s_ptr->next = second;
print_list(head);
}
/* List with even number of elements */
else if (!(f_ptr->next->next))
{
first = head;
second = s_ptr->next;
s_ptr->next = NULL;
/* Reverse the second half */
second = reverse_list(&second);
/* Compare the first & second half */
ret = are_identical(first, second);
/* Finally, construct the original list back */
second = reverse_list(&second);
s_ptr->next = second;
print_list(head);
}
return ret;
}
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다