#include <iostream>
#include<vector>
#include <stack>
using namespace std;
class Node
{
public:
int data;
Node* next;
};
int main()
{
int n;
cin >> n;
Node* head = new Node;
Node* ptr = new Node;
head = NULL;
// take the input for the linked list;
for (int i = 0; i< n ;i++)
{
int num;
cin >> num;
Node* temp = new Node;
temp->data = num;
temp->next = NULL;
if(head == NULL)
{
head = temp;
//head->next = NULL;
ptr = head;
}
else
{
ptr->next = temp;
ptr = temp;
}
// linked list made
}
Node* head1 = new Node;
head1 = head;
//ptr->data = NULL;
//ptr->next = NULL;
stack <int> stk;
ptr = head1;
while(ptr != NULL)
{
if(head1->data % 2 != 0)
{
head1 = head1->next;
}
else
{
ptr = head1;
while(ptr->data % 2==0 && ptr != NULL)
{
stk.push(ptr->data);
ptr = ptr->next;
}
while(head1 != ptr)
{
int n ;
n = stk.top();
head1->data = n;
head1 = head1->next;
stk.pop();
}
}
//head1 = ptr;
// replace the values again in the linked list
}
// print the linked list
while(head != NULL)
{
cout << head->data << " ";
head = head->next;
}
}
这是一个实践问题-1,用于HackerEarth上的单链列表。代码正在正确编译,但是遇到运行时错误,我无法弄清原因。
例如,如果列表是{24,18,2,5,7,16,12}返回的列表应该是{2,18,24,5,7,12,16}
链表中偶数编号的部分应颠倒,其余链表保持相同。
而且我还是编程新手,并且是第一次学习数据结构和算法,所以这次请原谅任何不好的缩进和愚蠢的错误。我保证会变得更好。
您的代码中存在大量逻辑问题。首先,不需要分配head
和ptr
。它们只是用作指向列表开头和结尾的指针(tail
是ptr
的更具描述性的名称),例如
更改行号62,例如-while(ptr != NULL && ptr->data % 2==0)