I catched segfault when run this code and can`t understand why. If firstly i use one time push(&head,3); then segfault is not catched, but it works bad for true
#include <iostream>
using namespace std;
struct Node
{
int data;
Node *next;
};
void push(Node **head,int data)
{
Node *tmp = new Node;
tmp->data = data;
tmp->next = (*head);
(*head) = tmp;
}
Node *getLast(Node *head)
{
if(head == nullptr)
{
return nullptr;
}
while(head->next)
{
head=head->next;
}
return head;
}
void show(const Node *head)
{
while(head!=nullptr)
{
cout << head->data << endl;
head = head->next;
}
}
void pushBack(Node *head,int data)
{
Node *last = getLast(head);
Node *tmp = new Node;
tmp->data = data;
tmp->next = nullptr;
last->next = tmp;
}
int main() {
Node *head=nullptr;
**//push(&head,2); /////if I use this then it works! but it not right.**
pushBack(head,10);
pushBack(head,2);
pushBack(head,3);
show(head);
return 0;
}
I tried to google it but it helpless. How to solve this problem?
Aucun commentaire:
Enregistrer un commentaire