首页 > 解决方案 > 单链表被核心转储的 Hackerearth 练习问题的代码

问题描述

    #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}

链表中偶数编号的部分应反转,使链表的其余部分保持不变。

此外,我对编程非常陌生,并且是第一次学习数据结构和算法,所以这次请原谅任何不好的缩进和愚蠢的错误。我保证会变得更好。

标签: c++segmentation-faultstacksingly-linked-list

解决方案


将第 62 行更改为 -while(ptr != NULL && ptr->data % 2==0)

你应该先检查ptr != null条件,如果它是假的,那么ptr->data由于短路评估将不会被执行。

https://en.wikipedia.org/wiki/Short-circuit_evaluation

虽然这将消除核心转储错误,但您不会获得所需的输出。你的代码也有逻辑错误。


推荐阅读