For starters the function does not make sense because it deletes nothing. In fact it tries to exclude a node from the list.
However the function has undefined behavior.
Let's assume that start
is equal to NULL
and index
is also equal to 0
. In this case due to these statements
if(index == 0){
current =start;
start = current->next;
^^^^^^^^^^^^^
}
there is an access to the memory using a null-pointer.
Now let's assume that the start
is not equal to NULL
and it is the only node in the list. And index
is equal to 1
.
In this case x
will be equal to 1
. And due to these statements
else if(index >0 && index <=x ){
current =start;
for(i=0; i<index-1; i++){
current = current ->next;
}
current->next= current->next->next;
^^^^^^^^^^^^^^^^^^^^
}
again there is an access to memory using a null-pointer.
So the function is entirely wrong.
Pay attention to that the function parameter should have an unsigned integer type. The most appropriate type is size_t
.
And if there is a function that uses a method by accessing a node by index then the list should keep the number of nodes in it.
If the program is indeed written as a C++ program then the function can look the following way as it is shown in the simplified demonstrative program below. Investigate it.
#include <iostream>
class List
{
public:
explicit List() = default;
List( const List & ) = delete;
List & operator =( const List & ) = delete;
void push_front( int value )
{
head = new Node { value, head };
}
std::ostream & out( std::ostream &os = std::cout ) const
{
for ( Node *current = head; current != nullptr; current = current->next )
{
os << current->value << " -> ";
}
os << "nullptr";
return os;
}
bool deleteAtIndex( size_t n )
{
Node **current = &head;
while ( *current != nullptr && n )
{
current = &( *current )->next;
--n;
}
bool success = *current != nullptr;
if ( success )
{
Node *tmp = *current;
*current = ( *current )->next;
delete tmp;
}
return success;
}
protected:
struct Node
{
int value;
Node *next;
} *head = nullptr;
};
std::ostream & operator <<( std::ostream &os, const List &lst )
{
return lst.out( os );
}
int main()
{
const size_t N = 10;
List lst;
for ( size_t i = N; i != 0; --i ) lst.push_front( int( i - 1 ) );
std::cout << lst << '\n';
std::cout << '\n';
for ( size_t i = N; i != 0; --i )
{
lst.deleteAtIndex( i - 1 );
std::cout << lst << '\n';
}
return 0;
}
The program output is
0 -> 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 -> nullptr
0 -> 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> nullptr
0 -> 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> nullptr
0 -> 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> nullptr
0 -> 1 -> 2 -> 3 -> 4 -> 5 -> nullptr
0 -> 1 -> 2 -> 3 -> 4 -> nullptr
0 -> 1 -> 2 -> 3 -> nullptr
0 -> 1 -> 2 -> nullptr
0 -> 1 -> nullptr
0 -> nullptr
nullptr