Linked_list_insertion

**Can Anyone tell me whether this function can be done recursively or not..?
1
2
3
4
5
6
7
void insert_front(node *&head, int x){ //head initialized as NULL in the main()
	node *temp;
	temp = new node;
	temp->value = x;	
	temp->next = head;
	head = temp;
}


closed account (o3hC5Di1)
Hi there,

Let's consider what this function does: It inserts an element at the front of a linked list.
Recursive functions are used for something that has a repetitive aspect to it. This function just creates a new head and sets it's "next" pointer to the previous head of the list. As an example, if you have a singly linked list, an insert_back() function could be recursive:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
void insert_back(node* current,  const int& x)
{
    if (current->next == nullptr) //base case, if at end of the list
    {
        node* new;
        new->value = x;
        new->next = nullptr;
        current->next = new;
    }
    else //if not at end of the list, do this function again but with the next node
    {
        insert_back(current->next, x);
    }
}


Note that this is just one implementation as an example of recursion, you could of course just use a while loop to iterate over the linked list. Hope that helps. please let us know if you have any further questions.

All the best,
NwN
Ya I created insert_back() using recursion; & its easy.
Still I'm thinking, there is no way to create insert_front() using recursion, but I'm trying and trying if there is any single way to do this.
So, your opinion is, its not possible because of no repetition there, right..?
Got it.
Thanks for nice explanation. :)
closed account (o3hC5Di1)
Hi there,

Your linked list will always need to keep a pointer to at least one element within it from where you can access all the other ones. It's custom to keep a pointer to the first element because that's where the list starts. Sometimes people also like to keep a pointer to the last element for fast insertion at the back, or in the case of a doubly linked list, to iterate the list in reverse.

Since, as you mentioned, there is no recurring task to do when you immediately know the first element of the list, I don't see any way you would even want to use recursion.

All the best,
NwN
Topic archived. No new replies allowed.