Why am I getting segmentation fault while implementing linked list? - c++

In this function, I get segmentation fault. I think it has something to do with memory allocation. What mistake am I making?
Now, if I initialize Node* a =NULL, i get my head pointer as NULL in the end.
struct Node {
int data;
struct Node* next;
Node(int x) {
data = x;
next = NULL;
}
};
Node* addTwoLists(Node* first, Node* second) {
// Code here
Node *a;
Node *head = a;
int bor = 0;
while(first->next && second->next) {
int ans = first->data + second->data;
a = new Node((ans%10)+bor);
bor = ans/10;
a=a->next;
first = first->next;
second = second->next;
}
return head;
}

a is uninitialized. You must not use a until you assign a value
you never again assign to head, so it could never be anything else.

It's not the allocation, it's the pointer use that is all wrong.
Here's how it should look. This code maintains a variable last which is the last node added to the list. You need this variable so you can at the end of the list. You were obviously trying to do this yourself, but got the logic wrong.
Node* addTwoLists(Node* first, Node* second) {
Node *last = NULL;
Node *head = NULL;
int bor = 0;
while(first->next && second->next) {
int ans = first->data + second->data;
Node* a = new Node((ans%10)+bor);
if (head == NULL) {
head = last = a; // first node, update head and end of list
}
else {
last->next = a; // add a to the end of the list
last = a; // update the end of the list
}
bor = ans/10;
first = first->next;
second = second->next;
}
return head;
}
Untested code.

For starters the variable head has indeterminate value and is not changed in the function.
Node *a;
Node *head = a;
Changing the variable a does not mean changing of the value of the expression a->next.
// ...
a = new Node((ans%10)+bor);
//...
a=a->next;
The function can be written the following way (without testing)
Node * addTwoLists( const Node *first, const Node *second )
{
const int Base = 10;
Node *head = nullptr;
int bor = 0;
Node **current = &head;
for ( ; first != nullptr && second != nullptr; first = first->next, second = second->next )
{
int sum = first->data + second->data + bor;
*current = new Node( sum % Base );
bor = sum / Base;
current = &( *current )->next;
}
if ( bor )
{
*current = new Node( bor );
}
return head;
}
Here is a demonstrative program
#include <iostream>
struct Node
{
explicit Node( int data, Node *next = nullptr ) : data( data ), next( next )
{
}
int data;
Node *next;
};
void push_front( Node **head, int x )
{
*head = new Node( x, *head );
}
Node * addTwoLists( const Node *first, const Node *second )
{
const int Base = 10;
Node *head = nullptr;
int bor = 0;
Node **current = &head;
for ( ; first != nullptr && second != nullptr; first = first->next, second = second->next )
{
int sum = first->data + second->data + bor;
*current = new Node( sum % Base );
bor = sum / Base;
current = &( *current )->next;
}
if ( bor )
{
*current = new Node( bor );
}
return head;
}
std::ostream & display_list( const Node *head, std::ostream &os = std::cout )
{
for ( ; head != nullptr; head = head->next )
{
os << head->data << ' ';
}
return os;
}
int main()
{
const int N = 10;
Node *list1 = nullptr;
Node *list2 = nullptr;
for ( int i = 1; i < N; i++ ) push_front( &list1, i );
for ( int i = N; --i != 0; ) push_front( &list2, i );
display_list( list1 ) << '\n';
display_list( list2 ) << '\n';
Node *list3 = addTwoLists( list1, list2 );
display_list( list3 ) << '\n';
}
Its output is
9 8 7 6 5 4 3 2 1
1 2 3 4 5 6 7 8 9
0 1 1 1 1 1 1 1 1 1

You may get segmentation fault for various reasons here.
If first or second is NULL then you will get segmentation fault. So make sure that if these two nodes are not NULL.
You didn't initialize a. So initialize it first.
And as you want head variable should contain starting node of the answer list so you need to assign node whenever you get start of the list.
Just add this line after a = new Node((ans%10)+bor);
if(head == NULL) head = a;

Related

Remove Singly Linked List at nth position

# include <iostream>
using namespace std;
class Node
{
public:
int d;Node*temp1;
Node*next;Node*temp2;
};
void insert(Node*&head,int x)
{
Node*node = new Node(); // allocate memory 2 node let node be an abstract data
node->d = x; // define data in the new node as new data (saving data define in there)
node->next = head; // Let next of the new node as head
head = node; // let pointer name head point new node
}
void print(Node*node)
{
while (node != NULL)
{
cout<<' '<<node->d;
node = node->next;
}
}
void Delete(Node*&head,int n) // Delete node at position
{
int i;Node*node=head;// temp1 points 2(n-1)th
if(n==1)
{
head = node->next; // head now points 2 second node.
return;
}
for(i=0;i<n-2;i++)
{
head = node->next;
} // temp1 points 2 (n-1)th Node
Node*nnode= node->next; // nth node temp1=node temp2=nnode
node-> next = nnode->next; //(n+1)th Node
}
int main()
{
Node*head = NULL; // Start with empty List
int a,n,i,x;
cin>>n;
for(i=0;i<n;i++)
{
cin>>x;
insert(*&head,x);
}
cout<<"Enter a position:";
cin>>a;
Delete(head,a);print(head);
}
The Output is:
3 // how many number that singly linked list can received
1 2 3 // define many numbers
Enter a position : 1
2 1 // false output it should be 2 3
The output should be:
3
1 2 3
Enter a position : 1
Linked List is 1->2->3
position 1 is remove // at any position we want 2 remove it will show that position we remove
2->3
Enter a position : 4
No data at 4th position
Linked List is 2->3
In the Delete function you have the loop
for(i=0;i<n-2;i++)
{
head = node->next;
}
Because you pass head by reference, you actively destroy the list with this loop. Furthermore since you have node = head earlier, the assignment is effectively head = head->next in the first iteration.
You need to use the variable node instead of head:
for(i=0;i<n-2;i++)
{
node = node->next;
}
You also need to protect against going beyond the end of the list:
for(i = 0; (i < n - 2) && (node->next != nullptr) ;i++)
For starters the declaration of the node of a singly linked list has redundant data members temp1 and temp2 that do not make sense.
The declarations can look like
struct Node
{
int data;
Node *next;
};
In this case the function insert (that you could call like
insert(head,x);
instead of
insert(*&head,x);
as you are doing) will look like
void insert( Node * &head, int x )
{
head = new Node { x, head };
}
In C++ (and in C) indices start from 0. So the function delete also shall accept indices starting from 0. The type of the corresponding parameter shall be an unsigned integer type for example size_t. Otherwise the user can pass a negative number as an index.
The function produces memory leaks because it in fact does not free allocated nodes. It can invoke undefined behavior when the pointer to the head node is equal to NULL. And in general the function does not make sense.
It can be defined the following way
bool Delete( Node * &head, size_t n )
{
Node **current = &head;
while ( *current && n-- )
{
current = &( *current )->next;
}
bool success = *current != nullptr;
if ( success )
{
Node *tmp = *current;
*current = ( *current )->next;
delete tmp;
}
return success;
}
Here is a demonstrative program.
#include <iostream>
struct Node
{
int data;
Node *next;
};
void insert( Node * &head, int x )
{
head = new Node { x, head };
}
bool Delete( Node * &head, size_t n )
{
Node **current = &head;
while ( *current && n-- )
{
current = &( *current )->next;
}
bool success = *current != nullptr;
if ( success )
{
Node *tmp = *current;
*current = ( *current )->next;
delete tmp;
}
return success;
}
std::ostream & print( Node * &head, std::ostream &os = std::cout )
{
for ( Node *current = head; current != nullptr; current = current->next )
{
os << current->data << " -> ";
}
return os << "null";
}
int main()
{
Node *head = nullptr;
for ( int i = 3; i != 0; i-- ) insert( head, i );
print( head ) << '\n';
size_t pos = 0;
if ( Delete( head, pos ) )
{
print( head ) << '\n';
}
else
{
std::cout << "No data at the position " << pos << '\n';
}
pos = 4;
if ( Delete( head, pos ) )
{
print( head ) << '\n';
}
else
{
std::cout << "No data at the position " << pos << '\n';
}
pos = 1;
if ( Delete( head, pos ) )
{
print( head ) << '\n';
}
else
{
std::cout << "No data at the position " << pos << '\n';
}
pos = 0;
if ( Delete( head, pos ) )
{
print( head ) << '\n';
}
else
{
std::cout << "No data at the position " << pos << '\n';
}
return 0;
}
Its output is
1 -> 2 -> 3 -> null
2 -> 3 -> null
No data at the position 4
2 -> null
null

How to make linked list with localy declared head?

I need to make a program which connects two linked lists before I used global pointer for the head of the list, but now I need to make it locally so I can insert new element(node) to each of them, but I have a problem with double-pointer, not sure when to use **, when * and when &. I can find any example similar to that.
Down below is what I have now.
#include<stdio.h>
#include<stdlib.h>
typedef struct element_{
int x;
struct element_ *next;
}element;
void insert(element **head, int x) {
element *new_ = new element;
element *p;
new_->x = x;
new_->next = NULL;
if (head == NULL) {
*head = new_;
return;
}
else {
for (p = *head;p->next != NULL;p = p->next) {}
p->next = new_;
}
}
int main(){
element **head = NULL;
insert(head,1);
insert(head,3);
insert(head,3);
insert(head,4);
for (element *p = *head;p != NULL;p = p->next){
printf("%d ", p->x);
}
}
There is nothing from C++ in the program except the operator new. So if to substitute the operator new for a call of malloc then you will get a pure C program.
So a C looking function insert can be defined like
void insert(element **head, int x)
{
element *new_ = new element;
new_->x = x;
new_->next = NULL;
while ( *head != NULL )
{
head = &( *head )->next;
}
*head = new_;
}
And in main you should write
element *head = NULL;
insert( &head, 1 );
insert( &head, 3 );
insert( &head, 3 );
insert( &head, 4 );
for (element *p = head; p != NULL; p = p->next )
{
printf("%d ", p->x);
}
Something that looks like a C++ function insert can be defined the following way
void insert( element * &head, int x )
{
element *new_ = new element { x, nullptr };
element **current = &head;
while ( *current != NULL )
{
current = &( *current )->next;
}
*current = new_;
}
And in main you should write
element *head = nullptr;
insert( head, 1 );
insert( head, 3 );
insert( head, 3 );
insert( head, 4 );
for (element *p = head; p != nullptr; p = p->next )
{
std::cout << p->x << ' ';
}
But to call the program indeed as C++ program then you should define the list as a class. Moreover if new nodes are appended to the tail of the singly-linked list then you should define the list a singly-linked two-sided list.
Here is a demonstrative program.
#include <iostream>
#include <functional>
class List
{
private:
struct Node
{
int data;
Node *next;
} *head = nullptr, *tail = nullptr;
public:
List() = default;
List( const List & ) = delete;
List & operator =( const List & ) = delete;
~List()
{
clear();
}
void clear()
{
while ( head )
{
delete std::exchange( head, head->next );
}
tail = head;
}
void push_front( int data )
{
head = new Node { data, head };
if ( !tail ) tail = head;
}
void push_back( int data )
{
Node *node = new Node { data, nullptr };
if ( tail )
{
tail = tail->next = node;
}
else
{
head = tail = node;
}
}
friend std::ostream & operator <<( std::ostream &os, const List &list )
{
for ( Node *current = list.head; current; current = current->next )
{
std::cout << current->data << " -> ";
}
return std::cout << "null";
}
};
int main()
{
List list;
list.push_back( 1 );
list.push_back( 3 );
list.push_back( 3 );
list.push_back( 4 );
std::cout << list << '\n';
}
Its output is
1 -> 3 -> 3 -> 4 -> null
Your code is nearly correct C code.
If head in main is a pointer to a pointer to element you have to dynamically allocate memory for it. It makes the code unnecessary complex. I made head in main a pointer to element. But you want to change it's value in insert so you have to pass by reference. The C way of pass by value is to pass the address. Also there is no new in C. Use malloc. And remember to clean up at the end. You have to call one free for each malloc.
If it really is supposed to be C++ code you have much to do. E.g, you wouldn't use pointers to pointers but references, you would use smart pointers instead of dynamic memory allocation, ...
Even though this is not the C++ way of programming it's also valid C++ code (I'm not sure about the headers).
#include <stdio.h>
#include <stdlib.h>
typedef struct element_{
int x;
struct element_ *next;
} element;
void insert(element **head, int x) {
element *new_ = malloc(sizeof(element));
element *p;
new_->x = x;
new_->next = NULL;
if (*head == NULL) {
*head = new_;
return;
} else {
for (p = *head;p->next != NULL;p = p->next) {}
p->next = new_;
}
}
void clean(element **p) {
if ((*p)->next != NULL) clean(&(*p)->next);
free(*p);
*p = NULL;
}
int main(){
element *head = NULL;
insert(&head, 1);
insert(&head, 3);
insert(&head, 3);
insert(&head, 4);
for (element *p = head; p != NULL; p = p->next){
printf("%d ", p->x);
}
clean(&head);
}

Error in creating a linked list from another linked list?

I'm creating a linked list from another linked list. But second linked list is not getting formed and there's a memory leak message on running the program.
Here's a section of the code that's troubling-
Node *rearrangeLinkedList(Node *head){
printLinkedList(head);
int lengthoflist = 0;
Node *temp = head;
while (temp!=NULL)
{
lengthoflist++;
temp=temp->next;
}
Node *secondList = NULL;
// just a variable node to store the head of second linked list-
Node *headOfSecondList = secondList;
int count=1;
while (count<=lengthoflist/2)
{
Node *temproary = new Node();
temproary->data=head->data;
temproary->next=NULL;
secondList=temproary;
secondList=secondList->next;
head=head->next;
count++;
}
printLinkedList(headOfSecondList);
}
printLinkedList() function is perfectly printing out the incoming list but not the second linked list.
After
Node *secondList = NULL;
Node *headOfSecondList = secondList;
you don't modify headOfSecondList any more. It will still be NULL when you call
printLinkedList(headOfSecondList); // => printLinkedList(NULL);
But you have another error in the copy-function:
while (count<=lengthoflist / 2)
{
Node *temproary = new Node();
temproary->data=head->data;
temproary->next=NULL;
secondList=temproary; // assign secondList
secondList=secondList->next; // secondList->next is temporary->next is NULL!!
head=head->next;
count++;
}
Here you create a bunch of nodes that all have a next of NULL. You do indeed leak memory here. secondList gets set to NULL at the end of each iteration and when temporary goes out of scope you don't have any pointers to the allocated memory left.
The following should work
// Build first node
Node *secondList = new Node();
secondList->data = head->data;
// advance by one
head = head->next;
// Now this points to the real head instead of NULL
Node *headOfSecondList = secondList;
int count=1;
while (count<=lengthoflist / 2 - 1 ) // -1 since we already handled the head above
{
Node *temproary = new Node(); // new node
temproary->data = head->data; // set data
temproary->next = NULL; // we have no next yet
secondList->next = temproary; // append temporary to secondList
secondList = secondList->next; //advance secondList
head = head->next; // advance head
count++;
}
printLinkedList(headOfSecondList);
I have skipped some validation here, but I hope the basic concept is clearer now.
If I have understood correctly the function tries to build a new list from the first half of nodes of an existed list.
If so then there is no need to calculate the number of nodes in the source list. This is inefficient.
You declared the function having the return type Node *.
Node *rearrangeLinkedList(Node *head );
but the function returns nothing.
Within the function the variable headOfSecondList is set once to nullptr and is never changed.
Node *secondList = NULL;
Node *headOfSecondList = secondList;
Within the while loop new nodes are not chained in a list. There is always changed the variable secondList and its data member next is always set to NULL. So there are numerous memory leaks.
while (count<=lengthoflist/2)
{
Node *temproary = new Node();
temproary->data=head->data;
temproary->next=NULL;
secondList=temproary;
secondList=secondList->next;
head=head->next;
count++;
}
The function can be written the following way.
Node * rearrangeLinkedList( Node *head )
{
Node *new_head = nullptr;
Node **tail = &new_head;
Node *first = head, *current = head;
while ( current != nullptr && ( current = current->next ) != nullptr )
{
current = current->next;
*tail = new Node();
( *tail )->data = first->data;
( *tail )->next = nullptr;
first = first->next;
tail = &( *tail )->next;
}
return new_head;
}
To demonstrate the approach without counting the number of nodes in the source list that as I already pointed out is inefficient here is a demonstrative program with a class template List.
#include <iostream>
template <typename T>
class List
{
private:
struct Node
{
T data;
Node *next;
} *head = nullptr;
public:
List() = default;
~List()
{
while ( head )
{
Node *current = head;
head = head->next;
delete current;
}
}
List( const List<T> & ) = delete;
List<T> & operator =( const List<T> & ) = delete;
void push_front( const T &data )
{
head = new Node { data, head };
}
List<T> & extract_half( List<T> &list ) const
{
Node **tail = &list.head;
while ( *tail ) tail = &( *tail )->next;
Node *first = this->head, *current = this->head;
while ( current != nullptr && ( current = current->next ) != nullptr )
{
current = current->next;
*tail = new Node { first->data, nullptr };
first = first->next;
tail = &( *tail )->next;
}
return list;
}
friend std::ostream & operator <<( std::ostream &os, const List &list )
{
for ( Node *current = list.head; current; current = current->next )
{
os << current->data << " -> ";
}
return os << "null";
}
};
int main()
{
List<int> list1;
const int N = 10;
for ( int i = N; i != 0; )
{
list1.push_front( --i );
}
std::cout << list1 << '\n';
List<int> list2;
list1.extract_half( list2 );
std::cout << list1 << '\n';
std::cout << list2 << '\n';
return 0;
}
The program output is
0 -> 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 -> null
0 -> 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 -> null
0 -> 1 -> 2 -> 3 -> 4 -> null

Swap Adjacent nodes in a Linked List Only by Manipulating pointers

I am trying to swap the adjacent nodes of a linked list i.e.
1->2->3->4->5 becomes 2->1->4->3->5
My function is:
node * swapper(node * &head)
{
if (head == NULL || head->next == NULL) return head;
node * t = head;
head= head->next;
head->next = t;
t->next = head->next;
node *previous = head->next->next, *current = previous->next;
while (current!=NULL&&previous!=NULL)
{
node * t1 = current,*t2=previous;
current->next = previous;
previous->next = t1->next;
previous = t1->next;
current = previous->next;
}
return head;
}
I know it can be done by swapping values but I have to do it in Constant space and without swapping the values.
I can't find why my function is not working.
The first thing that I can notice is that you need to swap those two lines:
head->next = t;
t->next = head->next;
because you are saying head->next = t so you are losing the connection to the rest of the linked list.
Also, inside the loop. There are several mistakes:
1- You're changing the next of current before obtaining it in previous, which means you're losing the link (like above)
2- You're not connecting them to the nodes that are before them.
My five cents.:)
Here is a demonstrative program that shows how to write a recursive function.
#include <iostream>
#include <functional>
struct node
{
int data;
struct node *next;
} *head;
void push_front( node * &head, int x )
{
head = new node { x, head };
}
void display( node *head )
{
for ( node *current = head; current; current = current->next )
{
std::cout << current->data << ' ';
}
std::cout << std::endl;
}
node * swapper( node * &head )
{
if ( head && head->next )
{
node *tmp = std::exchange(head, head->next );
std::exchange( tmp->next, std::exchange( tmp->next->next, tmp ) );
swapper( head->next->next );
}
return head;
}
int main()
{
const int N = 10;
for ( int i = N; i != 0; ) push_front( head, --i );
display( head );
display( swapper( head ) );
}
The program output is the following
0 1 2 3 4 5 6 7 8 9
1 0 3 2 5 4 7 6 9 8
Take into account that not all compilers support function std::exchange. So you will need to write it yourself.:)
If to write the main the following way
int main()
{
const int N = 10;
for ( int i = N; i != 0; ) push_front( head, --i );
display( head );
for ( node **current = &head; *current && ( *current )->next; current = &( *current )->next )
{
swapper( *current );
}
display( head );
}
then the following interesting output can be obtained.:)
0 1 2 3 4 5 6 7 8 9
1 3 5 7 9 8 6 4 2 0
node * swapper(node * &head)
{
if (head == NULL || head->next == NULL) return head;
node * t = head;
head= head->next;
t->next = head->next;
head->next = t;
node *previous = head->next->next, *current,*parent=head->next;
while (previous&&(current = previous->next))
{
node * t1 = current,*t2=previous;
previous->next = t1->next;
current->next = previous;
parent->next= current;
previous = t2->next;
//current = previous->next;
parent=t2;
}
return head;
}

Swapping adjacent elements of linked list

The below is my code to recursive swap the adjacent elements of a linked list. I am losing the pointer to every second element after the swap.
The input is 1->2->3->4->5->6->7, I expected the output 2->1->4->3->6->5->7,
but my output is 1->3->5->7.
void nodelist::swap(node* head)
{
node* temp = head->next;
if (head->next!= nullptr)
{
node* temp2 = temp->next;
temp->next = head;
head->next = temp2;
head = head->next;
temp = nullptr;
temp2 = nullptr;
swap(head);
}
}
Any help would be appreciated,thanks in advance.
In fact it is enough to swap only the data members of nodes. There is no need to swap the pointers themselves.
Nevertheless if to use your approach then the function can look like
void SwapList( node *head )
{
if ( head != nullptr && head->next != nullptr )
{
node *next = head->next;
std::swap( *head, *next );
std::swap( head->next, next->next );
SwapList( head->next->next );
}
}
Here is a demonstrative program
#include <iostream>
#include <utility>
struct node
{
int value;
node *next;
};
node * AddNode( node *head, int value )
{
head = new node { value, head };
return head;
}
void PrintList( node *head )
{
for ( ; head != nullptr; head = head->next )
{
std::cout << head->value << ' ';
}
}
void SwapList( node *head )
{
if ( head != nullptr && head->next != nullptr )
{
node *next = head->next;
std::swap( *head, *next );
std::swap( head->next, next->next );
SwapList( head->next->next );
}
}
int main()
{
node *head = nullptr;
for ( int i = 10; i != 0; )
{
head = AddNode( head, --i );
}
PrintList( head );
std::cout << std::endl;
SwapList( head );
PrintList( head );
std::cout << std::endl;
return 0;
}
The output is
0 1 2 3 4 5 6 7 8 9
1 0 3 2 5 4 7 6 9 8
You can use the shown function as a template (or base) for your function.
With no recursion:
void swap(node **head)
{
while (*head && (*head)->next)
{
node* tmp = *head;
*head = tmp->next;
tmp->next = (*head)->next;
(*head)->next = tmp;
head = &tmp->next;
}
}
Invoke swap( & list_head_ptr).
Alternatively, you can pass the head pointer by reference-to-pointer and utilize a local pointer-to-pointer member:
void swap(node*& head)
{
node **pp = &head;
while (*pp && (*pp)->next)
{
node* tmp = *pp;
*pp = tmp->next;
tmp->next = (*pp)->next;
(*pp)->next = tmp;
pp = &tmp->next;
}
}
and invoke as swap(list_head_ptr). Either method works.
Using recursion:
void nodelist::swap(node** head) {
if (!*head || !(*head)->next) return;
node* const sw = (*head)->next;
(*head)->next = sw->next;
sw->next = *head;
*head = sw;
swap(&(sw->next->next));
}
If head is the pointer which stores the address of firstNode (value=1), then try following function:
void nodelist::swap(node* head){
node* temp = head->next; //head->next is first-node which needs to switch with it's next node
if (temp!= nullptr && temp->next!=nullptr){
head->next=temp->next; //move second node to first
temp->next = head->next->next; //put second's next in first's
head->next->next = temp; //and first will be second's next
temp = nullptr; // swaping done
swap(head->next->next); //do it for next couple
}
}
http://coliru.stacked-crooked.com/a/e1cc0d02b5599da4
OR
http://coliru.stacked-crooked.com/a/a1e200b687825d80
If head itself is the firstNode (value=1), then passing head by value will not work, either you need to pass it by address/reference OR do it like in following link:
http://coliru.stacked-crooked.com/a/a1e200b687825d80