下面是檢查如果鏈接列表是迴文是否代碼。我寫的代碼很簡單但仍冗長,因爲它有很多冗餘代碼。我是否可以REDUCE複雜性此代碼根據大O保持相同的邏輯。要檢查鏈接列表作爲迴文沒有使用STACK
只是因爲我不得不跳過的中間節點奇數鏈表我最終使得代碼冗餘的情況。只有我在奇鏈表的代碼添加額外的部分是
`head_new = temp->next;
// NEEDED TO SHIFT ONE POSITION SINCE MIDDLE NODE DOES NOT NEED ANY CHECKING!!!`
。
有沒有什麼辦法可以讓我的代碼整齊,少用多餘的代碼。
void linklist::palindrome()
{
node *prev = NULL;
node *curr = new node;
node *next = new node;
node *head_new = new node;
node *temp;
temp = head;
curr = head;
int t = 0,flag=0,flag_new=0;
while (curr != NULL) // calculating the length of llinked list
{
curr = curr->next;
t++;
}
curr = head; // Making sure curr is pointing to the head
if (t % 2 == 0) // checking whether the linked list is even or odd
{
flag = 1;
}
if (flag == 1) // if linked list is even
{
for (int i = 0; i < t/2 ; i++) // traversing till the half
{
temp = temp->next;
}
head_new = temp; // making sure head_new points to the head of other half
for (int i = 0; i < t/2; i++) // logic to do the reverse first half of the linked list
{
next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
}
head->next = NULL;
head = prev;
while (head && head_new) // comparing the reversed first half with the second half
{
if (head->data != head_new->data)
{
cout << "Not palindrome";
flag_new = 1;
break;
}
else
{
head = head->next;
head_new = head_new->next;
}
}
if (flag_new==0)
cout << "Palindrome";
}
else
{
for (int i = 0; i < t/2; i++)// logic to do the traverse first half of the linked list
{
temp = temp->next;
}
head_new = temp->next; // ***NEEDED TO SHIFT ONE POSITION SINCE MIDDLE NODE DOES NOT NEED ANY CHECKING!!!***
for (int i = 0; i < t/2; i++) // logic to do the reverse first half of the linked list
{
next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
}
head->next = NULL;
head = prev;
while (head && head_new)// comparing the reversed first half with the second half
{
if (head->data != head_new->data)
{
cout << "Not palindrome";
flag_new = 1;
break;
}
else
{
head = head->next;
head_new = head_new->next;
}
}
if (flag_new == 0)
cout << "Palindrome";
}
}
搬出鏈表管理的一類。 –
爲什麼反對票。我已經寫好了所有的評論和一切。我需要知道如果保持相同的邏輯能否降低複雜性。 – Unbreakable
「減少複雜性」和「更整潔的方式」(擺脫「更多」,順便說一句)是兩個正交的東西。所以你的問題基本上使得它聽起來像:「這是我的代碼,請盡你所能來改善任何你想到的每一個方面」。這可能是反對票的主要原因(儘管我本人沒有參加)。請問一個更具體的問題。另外,請指出爲什麼你希望不使用堆棧,因爲使用給定的鏈表的數據結構,它可以**實際上使你的代碼更加整潔。 –