You are on page 1of 4

Name-SIDDHANT PRATAP SINGH

Reg_no-18BCE1123

Digital Assignment -1

1.

Write a “C” function to insert a node “t” before a node pointed to by “X” in a single linked list “L”.

ANS-

#include <iostream>

using namespace std;

struct Node {

int data;

struct Node* next;

};

int size = 0;

Node* newNode(int data)

Node* newNode = new Node();

newNode->data = data;

newNode->next = NULL;

return newNode;

void push(Node** head, int data)

Node* newnode = new Node();

Node *last = *head;

newnode->data = data;

newnode->next = NULL;

if (*head == NULL)

*head= newnode;

return;
}

while (last->next != NULL)

last = last->next;

last->next = newnode;

return;

void insertbtw(Node** root, int pos, int data)

if (pos < 1 || pos > size + 1)

cout << "Invalid position!" << endl;

else

while (pos--)

if (pos == 0)

Node* temp = newNode(data);

temp->next = *root;

*root = temp;

else

root = &(*root)->next;

size++;

void print(struct Node* root)

while (root != NULL)

{
cout << " " << root->data;

root = root->next;

cout << endl;

int main()

Node* head = NULL;

int n,i,a[n];

cout<<"Enter the no element to inserted:";

cin>>n;

for(i=0;i<n;i++)

cin>>a[i];

push(&head,a[i]);

size = n;

int data,pos;

cout<<"Enter the data to be inserted:";

cin>>data;

cout<<"Enter the position to be inserted:";

cin>>pos;

insertbtw(&head, pos, data);

print(head);

return 0;

You might also like