# 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
Related
I've come across a problem in dynamic programming in which we are asked to delete nodes of a circular LinkedList, in the following manner.
Delete the first node then skip one and delete the next, then skip two and delete the next, then skip three and delete the next and it continues until we are left with only one node, and that one node is our answer.
For example, if we have 5 nodes, then the nodes will be deleted in the following order – 1 3
2 5 4, and the last node would be 4.
Similarly, if we have 4 nodes, then the nodes will be deleted in the following order – 1 3 4
2, and the last node would be 2.
This is a screenshot of the part of the code that requires improvement
using this code in c++, I've been successful in solving the problem but I want to free the memory using delete command as I delink a node. Can anyone please help me to solve this problem by improving this code (while using minimal memory)?
The node can be deleted by declaring another pointer, but that would only increase the memory usage, which I don't want at the moment.
The entire code is given below
#include<iostream>
using namespace std;
class linked {
public:
int x;
linked* next;
//methods
linked(int p); //constructor
static void insert(linked*& head, int p);//method to insert new node
static int print(linked* head);//method to print the result
static void del(linked*head, int size) {//method to delete all the undesired nodes
linked* temp = head;
while (temp->next != head) {//traversing until we find the node just behind the node we want to del
temp = temp->next;
}
for(int i=1;i < size;i++) {
for (int k = 1; k < i; k++) {//del nodes with increment
temp = temp->next;
}
temp->next = temp->next->next; //delinking the
}
}
};
int main() {
int no_of_nodes;
cout << "enter the number of nodes you want to have" << endl;
cin >> no_of_nodes;
linked* head = new linked(1);
for (int i = 1; i <= no_of_nodes; i++) {
linked::insert(head, i);//for inserting nodes, as desired by the user
}
linked::del(head, no_of_nodes);
cout<< linked::print(head);
}
linked::linked(int p) {
x = p;
next = NULL;
}
void linked::insert(linked*& head, int p) {
linked* temp = head;
linked* n = new linked(p);//for the new node
if (p == 1) {
head->next = head;
return;
}
while (temp->next != head) {
temp = temp->next;
}
temp->next = n;
n->next = head;
}
int linked::print(linked* head) {
linked* temp = head;
for (int i = 0; i < 25; i++) {//this can go longer(or shorter), i limited it to 25 only, just to ensure that it is a circular linked list
temp = temp->next;
if (temp == temp->next) {
return temp->x;
}
}
cout << endl;
}
P.S. The problem was taken from ICPC Asia Topi 2022, link: (https://giki.edu.pk/wp-content/uploads/2022/03/ICPC_Day_2.pdf)
It seems neither professional programmer are going to help you.:)
So we, beginners, should help each other.:)
You should declare a class of the circular singly-linked list with non-static member functions.
As for the task to remove all elements from the circular singly-linked list except one using the described algorithm then I can suggest the following approach.
At first within the function remove the cycling. This will make easy to remove elements from the circular singly-linked list.
After all elements except one will be removed then restore the cycling.
Here is a demonstration program.
#include <iostream>
#include <utility>
#include <stdexcept>
class CircularList
{
private:
struct Node
{
int data;
Node *next;
} *head = nullptr;
public:
CircularList() = default;
CircularList( const CircularList & ) = delete;
CircularList &operator =( const CircularList & ) = delete;
~CircularList()
{
clear();
}
void clear()
{
if (head)
{
Node *current = head;
do
{
delete std::exchange( current, current->next );
} while (current != head);
head = nullptr;
}
}
void insert( int data )
{
Node *new_node = new Node{ data };
if (not head)
{
new_node->next = new_node;
head = new_node;
}
else
{
Node *current = head;
while (current->next != head) current = current->next;
new_node->next = head;
current->next = new_node;
}
}
const int & top() const
{
if (not head)
{
throw std::out_of_range( "Error. The list is empty." );
}
return head->data;
}
void remove_except_one()
{
if (head)
{
Node *last = head;
while (last->next != head) last = last->next;
last->next = nullptr;
Node **current = &head;
for (size_t n = 0; head->next != nullptr; ++n)
{
for (size_t i = 0; i != n; i++)
{
current = &( *current )->next;
if (*current == NULL) current = &head;
}
Node *tmp = *current;
// The statement below is uncommented for the debug pyrpose.
std::cout << ( *current )->data << '\n';
*current = ( *current )->next;
if (*current == nullptr) current = &head;
delete tmp;
}
head->next = head;
}
}
friend std::ostream &operator <<( std::ostream &os, const CircularList &list )
{
if (list.head)
{
const Node *current = list.head;
do
{
os << current->data << " -> ";
current = current->next;
} while (current != list.head);
}
return os << "null";
}
};
int main()
{
CircularList list;
for (int i = 0; i < 5; i++)
{
list.insert( i + 1 );
}
std::cout << "The list: ";
std::cout << list << '\n';
list.remove_except_one();
std::cout << "The list: ";
std::cout << list << '\n';
list.clear();
std::cout << '\n';
for (int i = 0; i < 4; i++)
{
list.insert( i + 1 );
}
std::cout << "The list: ";
std::cout << list << '\n';
list.remove_except_one();
std::cout << "The list: ";
std::cout << list << '\n';
}
The program output is
The list: 1 -> 2 -> 3 -> 4 -> 5 -> null
1
3
2
5
The list: 4 -> null
The list: 1 -> 2 -> 3 -> 4 -> null
1
3
4
The list: 2 -> null
Within the function remove_except_one this statement
std::cout << ( *current )->data << '\n';
is present for the debug purpose only. You may remove or comment it if you want.
There are some problems with your code:
1) empty list should be nullptr
In main:
linked* head = new linked(1);
should be
linked* head = nullptr;
You start with an empty list. You do not know what data you will insert first and you assume the first value inserted will be 1. With this change you also have to change your insert:
if (p == 1) {
has to check
if (head == nullptr) {
2) replace head with tail
In a circular single linked list you always need the previous node to delete a node or to insert at the head. That means you have to traverse the whole list when given the head to find the previous. This is rather slow, so store the tail of the list instead. Then the head is tail->next and you can delete the head or insert at the head directly.
3) del breaks head
static void del(linked*head, int size) {
If this deletes the first node in the list then the head the caller passed in becomes a dangling pointer. There is no way to update the pointer the caller holds for the list. Just like with insert you need to pass in a reference:
static void del(linked*&head, int size) {
Now for your problem of how to delete the node without extra memory:
You can't. You always need extra memory to temporarily store the node to be deleted while you fix up the links in the list and then delete it. You already needed that extra memory to find the tail of the list and you called it temp.
static void del(linked*&tail) {
if (tail == nullptr) return; // no list, nothing to delete
for (std::size_t skip = 0; tail->next != tail; ++skip) { // keep going till only one node is left
for(std::size_t i = 0; i < skip; ++i) tail = tail->next; // skip nodes
// delete node
linked* temp = tail->next;
tail->next = tail->next->next;
delete temp;
}
}
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);
}
I want to implement the sorted bag(collection) data structure(with a singly-linked list) in C++ and I have a problem when I want to test the add function. This is the test:
SortedBag sb(relation1); (relation1 is e1<=e2)
sb.add(5);
std::cout << sb.size()<<" ";
sb.add(6);
std::cout << sb.size() << " ";
sb.add(0);
std::cout << sb.size() << " ";
sb.add(5);
std::cout << sb.size() << " ";
sb.add(10);
std::cout << sb.size() << " ";
sb.add(8);
std::cout << sb.size() << " ";
And it will print 1 2 3 3 4 5 instead of 1 2 3 4 5 6.
This is the add function:
void SortedBag::add(TComp e) {
Node* auxiliarElement = new Node;
Node* CheckSLL = new Node;
int flagStop = 1;
if (this->head == nullptr)
{
auxiliarElement->value = e;
auxiliarElement->freq = 1;
auxiliarElement->next = nullptr;
this->head = auxiliarElement;
}
else {
CheckSLL = this->head;
while (CheckSLL->next != nullptr && rel(CheckSLL->value, e))
{
if (CheckSLL->value == e) {
CheckSLL->freq += 1;
flagStop = 0;
break;
}
CheckSLL = CheckSLL->next;
}
if (CheckSLL == this->head && flagStop)
{
auxiliarElement->value = e;
auxiliarElement->freq = 1;
auxiliarElement->next = this->head;
this->head = auxiliarElement;
flagStop = 0;
}
if (CheckSLL->value == e && flagStop)
{
CheckSLL->freq += 1;
flagStop = 0;
}
if (flagStop) {
auxiliarElement->value = e;
auxiliarElement->freq = 1;
auxiliarElement->next = nullptr;
CheckSLL->next = auxiliarElement;
}
}
}
The size() functions works fine, I will post that too:
int SortedBag::size() const {
int Size = 0;
Node* goThrough = new Node;
goThrough = this->head;
while (goThrough != nullptr) {
Size += goThrough->freq;
goThrough = goThrough->next;
}
return Size;
}
And I can't find out why it doesn't add the frequency from the second 5. Can somebody help me, please? (the struct Node has value,freq and a pointer to the next Node)
For starters these statements
Node* CheckSLL = new Node;
and
Node* goThrough = new Node;
result in memory leaks.
Also this output
And it will print 1 2 3 3 4 5.
does not correspond to the sequence of entered data because the function size counts the total value of frequencies
Size += goThrough->freq;
So as 6 elements were inserted in the list then the output should be
1 2 3 4 5 6
The relation should be specified like e1 < e2 not like e1 <= e2
The function add can be defined very simply. I assume that the relation corresponds to the operator <.
void SortedBag::add( TComp e )
{
Node **current = &this->head;
while ( *current != nullptr && rel( ( *current )->value, e ) )
{
current = &( *current )->next;
}
if ( *current == nullptr || rel( e, ( *current )->value ) )
{
Node *new_node = new Node;
new_node->value = e;
new_node->freq = 1;
new_node->next = *current;
*current = new_node;
}
else
{
++( *current )->freq;
}
}
And you should decide whether the function size returns frequencies or the number of nodes in the list.
Here is a demonstrative program.
#include <iostream>
#include <functional>
template <typename T, typename Comparison = std::less<T>>
class List
{
private:
struct Node
{
T value;
size_t freq;
Node *next;
} *head = nullptr;
Comparison cmp;
public:
explicit List() : cmp( Comparison() )
{
}
explicit List( Comparison cmp ) : cmp( cmp )
{
}
~List()
{
while ( this->head != nullptr )
{
Node *current = this->head;
this->head = this->head->next;
delete current;
}
}
List( const List & ) = delete;
List & operator =( const List & ) = delete;
void add( const T &value );
friend std::ostream & operator <<( std::ostream &os, const List &list )
{
for ( Node *current = list.head; current != nullptr; current = current->next )
{
os << current->value << ':' << current->freq << " -> ";
}
return os << "null";
}
};
template <typename T, typename Comparison>
void List<T, Comparison>::add( const T &value )
{
Node **current = &this->head;
while ( *current != nullptr && cmp( ( *current )->value, value ) )
{
current = &( *current )->next;
}
if ( *current == nullptr || cmp( value, ( *current )->value ) )
{
Node *new_node = new Node { value, 1, *current };
*current = new_node;
}
else
{
++( *current )->freq;
}
}
int main()
{
List<int> list;
list.add( 5 );
list.add( 6 );
list.add( 0 );
list.add( 5 );
list.add( 10 );
list.add( 8 );
std::cout << list << '\n';
return 0;
}
The program output is
0:1 -> 5:2 -> 6:1 -> 8:1 -> 10:1 -> null
I'm practicing linked list today, trying my best to understand it, so I tried making one singly linked list where I can add at the beginning,middle,and end, it also initializes to add one if the list is empty then printing the result.
I already use functions for this insertion and display of inputs or outputs but still the outputs result to nothing, event the printing the list, i tried to change the position of
node* head = NULL;
and still nothing happens
void insert(node* head, int numb, int size, int pos)
{
node* temp = new node();
int counter;
temp->number = numb;
if (head == NULL) {
head = temp;
}
else {
int counter = 0;
node* current = head;
node* trail = NULL;
while (counter++) {
if (counter == pos) {
temp->next = current;
trail->next = temp;
break;
}
else {
trail = current;
current = current->next;
continue;
}
}
}
size++;
}
void printlist(node* head)
{
while (head != NULL) {
cout << " " << head->number;
head = head->next;
}
}
int main()
{
node* head = NULL;
int numb, size = 0, pos;
numb = 5;
pos = 0;
insert(head, numb, size, pos);
printlist(head);
numb = 6;
pos = 2;
insert(head, numb, size, pos);
printlist(head);
}
I expect the output for the first is 5 then the second is 5 6.
The pointer you pass in insert(node* head is just a copy of the pointer in main. Any modifications to this pointer (e.g. head = temp) will not be reflected in main.
You need to pass either a pointer to the pointer or a reference to the pointer, for example:
void insert(node*& head, int numb, int size, int pos)
The function is invalid and in general has undefined behavior. For example this statement in the function
size++;
does not make sense because the parameter size does not have a referenced type. That is the function deals with a copy of its argument. The object size passed as an argument to the function will stay unchanged. And as a result the variable size within main will be always equal to 0.
Or within the loop
node* trail = NULL;
while (counter++) {
if (counter == pos) {
temp->next = current;
trail->next = temp;
//...
for the position equal to 1 the node trail is equal to NULL so this statement
trail->next = temp;
has undefined behavior.
Also the head node in main is not changed by the function because it is passed to the function by value. That is again the function deals with a copy of the head node.
And it is a bad idea to define the variables size and pos as having a signed integer type. In this case you have to check within the function whether the value of the parameter pos is greater than or equal to 0.
The function can be defined as it is shown in the demonstrative program below.
#include <iostream>
struct node
{
int number;
node *next;
};
void insert( node * &head, int number, size_t &size, size_t pos )
{
node **current = &head;
while ( pos != 0 && *current != nullptr )
{
--pos;
current = &( *current )->next;
}
*current = new node { number, *current };
++size;
}
std::ostream & printlist( const node* head, std::ostream &os = std::cout )
{
for ( const node *current = head; current != nullptr; current = current->next )
{
os << current->number << ' ';
}
return os;
}
int main()
{
node *head = nullptr;
size_t size = 0;
size_t pos;
int numb;
numb = 5;
pos = 0;
insert( head, numb, size, pos );
printlist(head) << '\n';
numb = 6;
pos = 2;
insert( head, numb, size, pos );
printlist(head) << '\n';
numb = 4;
pos = 0;
insert( head, numb, size, pos );
printlist(head) << '\n';
numb = 10;
pos = 2;
insert( head, numb, size, pos );
printlist(head) << '\n';
std::cout << "There are " << size << " nodes in the list.\n";
return 0;
}
The program output is
5
5 6
4 5 6
4 5 10 6
There are 4 nodes in the list.
Pay attention to that you need to write also a function that will free all allocated memory for the list.
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;