反转链表会影响main()中原始列表的头指针。因此无法比较反向列表和原始列表-C ++

问题描述 投票:-1回答:1

我正在编写一个程序来检查单链表是否是回文。为此,我想反转列表,并将其与原始列表进行比较。但是我面临以下问题-当我反转列表时,原始列表的头指针被修改,并指向NULL。因此,当我有以下原始列表时,反转原始列表后会发生以下情况:

  1. 原始列表:1-> 1-> 2-> 1-> NULL
  2. 反向列表:1-> 2-> 1-> 1-> NULL
  3. 但是,在调用reverseList之后,原始列表变为:1-> 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函数中发生以下情况:

  1. [head2设置为:1->2->1->1->NULL
  2. [headhead1设置为1->NULL] >>
  3. 而且我无法再比较两个链表,以检查它们是否相互回文(因为比较将给我错误的结果)。

这一切都是因为我在temp1->next=NULL功能中设置了reverseList

您知道如何正确终止reverseList函数中的列表,以免影响原始列表吗?

非常感谢!

我正在编写一个程序来检查单链表是否是回文。为此,我想反转列表,并将其与原始列表进行比较。但是我面临以下问题-...

c++ singly-linked-list
1个回答
0
投票

以下是更正后的代码,其中合并了原始列表的深层副本(在isPalindrome函数中:]

© www.soinside.com 2019 - 2024. All rights reserved.