0% found this document useful (0 votes)
2 views2 pages

Linklist Insertion

The document contains C++ code for a singly linked list implementation, including functions to insert nodes at the front, after a given node, and at the end of the list. It defines a Node class and provides a print function to display the list. The main function demonstrates creating a linked list and inserting a node after the head node, followed by printing the list.

Uploaded by

Sajid Ali
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views2 pages

Linklist Insertion

The document contains C++ code for a singly linked list implementation, including functions to insert nodes at the front, after a given node, and at the end of the list. It defines a Node class and provides a print function to display the list. The main function demonstrates creating a linked list and inserting a node after the head node, followed by printing the list.

Uploaded by

Sajid Ali
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

#include <iostream>

using namespace std;

class Node
{
public:
int value;
Node* Next;
};
void printlist(Node* n)
{
while (n!=NULL)
{
cout << n->value << endl;
n = n->Next;
}
}
void insertatthefront (Node **head, int newvalue)
{
Node* newnode = new Node();
newnode->value = newvalue;

newnode->Next = *head;
*head = newnode;
}
void insertafter(Node *previous, int nodevalue)
{
//check if previous node is null
if (previous == NULL)
{
cout << "previous cannot be null" << endl;
return;
}
//prepare node
Node* newnode = new Node();
newnode->value = nodevalue;

//insert new node after previous


newnode->Next = previous->Next;
previous->Next = newnode;
}
void insertatend(Node**head, int newvalue)
{
//prepare a new node
Node* newnode = new Node();
newnode->value = newvalue;
newnode->Next = NULL;
//if linked list is empty, new node will be head node
if (*head == NULL)
{
*head = newnode;
return;
}
//find last node
Node* last = *head;
while (last->Next != NULL)
{
last = last->Next;
}
//insert newnode afer last node
last->Next = newnode;
}
int main()
{
Node* head = new Node();
Node* second = new Node();
Node* third = new Node();

head->value = 1;
head->Next = second;
second->value = 2;
second->Next = third;
third->value = 3;
third->Next = NULL;
//insertatthefront(&head, -1);
//insertatend(&head, 4);
insertafter(head, -6);
printlist(head);
}

You might also like