Linked list creation , deletion, insertion, and reversing of linked list
Adarsh
Posted on July 24, 2022
Linked list creation , deletion, insertion, and reversing of linked list
#include <iostream>
using namespace std;
struct Node
{
int data;
struct Node *next;
};
struct Node *head;
void printList()
{
Node *temp = head;
while (temp != NULL)
{
cout << temp->data << " ";
temp = temp->next;
}
cout << endl;
}
void insertNode(int data, int pos)
{
Node *temp1 = new Node();
temp1->data = data;
if (pos == 1)
{
temp1->next = head;
head = temp1;
return;
}
Node *temp2 = head;
for (size_t i = 0; i < pos - 2; i++)
{
temp2 = temp2->next;
}
temp1->next = temp2->next;
temp2->next = temp1;
}
void deleteNode(int pos)
{
Node *temp1 = head;
if (pos == 1)
{
head = temp1->next;
delete temp1;
return;
}
for (int i = 0; i < pos - 2; i++)
{
temp1 = temp1->next;
}
Node *temp2 = temp1->next;
temp1->next = temp2->next;
delete temp2;
}
void reverseList()
{
Node *prev, *current, *next;
current = head;
prev = NULL;
while (current != NULL)
{
next = current->next;
current->next = prev;
prev = current;
current = next;
}
head = prev;
}
int main()
{
head = NULL;
for (int i = 1; i < 6; i++)
{
insertNode(i, i);
}
printList();
deleteNode(3);
printList();
reverseList();
printList();
return 0;
}
💖 💪 🙅 🚩
Adarsh
Posted on July 24, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
privacy Caught in the Crunch My Journey from Snacks to 2 Million Exposed Users Privacy
November 30, 2024
devchallenge Submission for the DevCycle Feature Flag Challenge: Feature Flag Funhouse
November 30, 2024