我正在编写一个程序来检查单链表是否是回文。为此,我想反转列表,并将其与原始列表进行比较。但是我面临以下问题-当我反转列表时,原始列表的头指针被修改,并指向NULL。因此,当我有以下原始列表时,反转原始列表后会发生以下情况:
这是因为我有以下代码来反转列表:
ListNode* reverseList(ListNode* head)
{
ListNode* temp = head;
ListNode* temp1 = temp;
ListNode* current = NULL, * nextNode = NULL;
if (temp)
current = temp->next;
if (current)
nextNode = current->next;
while (current)
{
current->next = temp;
temp = current;
current = nextNode;
if (current)
nextNode = current->next;
}
temp1->next = NULL;
return temp;
}
我在上面的temp1->next = NULL
函数中执行了reverseList
(函数中的第二行)后,原始列表的头被修改,并且原始列表现在指向1-> NULL,而不是1 -> 1-> 2-> 1-> NULL。
如果有完整代码,则调用函数reverseList:
struct ListNode
{
int val;
ListNode* next;
ListNode(int x):val(x),next(NULL){}
};
ListNode* reverseList(ListNode* head)
{
ListNode* temp = head;
ListNode* temp1 = temp;
ListNode* current = NULL, * nextNode = NULL;
if (temp)
current = temp->next;
if (current)
nextNode = current->next;
while (current)
{
current->next = temp;
temp = current;
current = nextNode;
if (current)
nextNode = current->next;
}
temp1->next = NULL;
return temp;
}
bool isPalindrome(ListNode* head) {
//reverse the Linked list and then compare the two lists.
if (head == NULL)
return true;
ListNode* head1 = head;
ListNode* head2 = reverseList(head);
while (head1 && head2)
{
if (head1->val != head2->val)
return false;
head1 = head1->next;
head2 = head2->next;
}
return true;
}
int main()
{
ListNode* head = new ListNode(1);
head->next = new ListNode(1);
head->next->next = new ListNode(2);
head->next->next->next = new ListNode(1);
head->next->next->next->next = NULL;
bool palindrome = isPalindrome(head);
cout << palindrome << endl;
return 0;
}
因此,当reverseList函数返回时,在isPalindrome
函数中发生以下情况:
head2
设置为:1->2->1->1->NULL
head
和head1
设置为1->NULL
] >>而且我无法再比较两个链表,以检查它们是否相互回文(因为比较将给我错误的结果)。
这一切都是因为我在temp1->next=NULL
功能中设置了reverseList
。
您知道如何正确终止reverseList
函数中的列表,以免影响原始列表吗?
非常感谢!
我正在编写一个程序来检查单链表是否是回文。为此,我想反转列表,并将其与原始列表进行比较。但是我面临以下问题-...
以下是更正后的代码,其中合并了原始列表的深层副本(在isPalindrome
函数中:]