xxxxxxxxxx
struct Node
{
int data;
Node *next;
Node(int val)
{
data = val;
next = NULL;
}
};
void insertAtTail(Node *&head, int val)
{
Node *n = new Node(val);
Node *temp = head;
if (temp == NULL)
{
head = n;
return;
}
while (temp->next != NULL)
{
temp = temp->next;
}
temp->next = n;
}
void insertAtHead(Node *&head, int val)
{
Node *n = new Node(val);
n->next = head;
head = n;
}
void insertAtPos(Node *&head, int val, int pos)
{
Node *n = new Node(val);
Node *temp = head;
Node *temp1 = NULL;
int count = 0;
while (temp != NULL && count != pos)
{
count++;
temp1 = temp;
temp = temp->next;
}
temp1->next = n;
n->next = temp;
}
// In main function use above functions like this
Node *head = NULL;
insertAtTail(head, 1);
insertAtTail(head, 2);
insertAtTail(head, 3);
xxxxxxxxxx
// All Three Conditons
// -> Insert at head
// -> Insert at middle
// -> Insert at tail
void InsertAtTail(Node *&head, Node *&tail, int data)
{
// If Linked List is empty //
if (tail == NULL)
{
// Creating a new node //
Node *newNode = new Node(data);
// if LL has only one node then head and tail will be the same node //
head = newNode;
tail = newNode;
return;
}
Node *newNode = new Node(data);
// assign next node of tail to new node //
tail->next = newNode;
// replacing tail with new node as it is the Last node (Tail) now //
tail = newNode;
}
void InsertAtHead(Node *&head, Node *&tail, int data)
{
// If Linked List is empty //
if (head == NULL)
{
// Creating a new node //
Node *newNode = new Node(data);
// if LL has only one node then head and tail will be the same node //
head = newNode;
tail = newNode;
// returning from the function //
return;
}
// Create a new node //
Node *newNode = new Node(data);
// assign next node to head //
newNode->next = head;
// replace head with new node //
head = newNode;
}
void InsertAtMiddle(Node* &head , Node* &tail , int data , int positon){
int len = FindLength(head);
if(positon==0){
InsertAtHead(head,tail,data);
return;
}
else if(positon==len){
InsertAtTail(head,tail,data);
return;
}
int i = 1;
Node* prev = head;
while(i < positon){
prev = prev ->next;
i++;
}
Node *cur = prev -> next;
Node* newNode = new Node(data);
prev ->next = newNode;
newNode ->next = cur;
}
xxxxxxxxxx
/*
class Node{
int data;
Node next;
Node(int x){
data = x;
next = null;
}
}
*/
class Solution1
{
//Function to insert a node at the beginning of the linked list.
Node insertAtBeginning(Node head, int x)
{
// code here
Node n = new Node(x);
n.next=head;
head = n;
return head;
}
//Function to insert a node at the end of the linked list.
Node insertAtEnd(Node head, int x)
{
// code here
Node node = new Node(x);
if(head == null)
{
head = node;
return head;
}
Node temp = head;
while(temp.next!=null)
{
temp = temp.next;
}
temp.next = node;
return head;
}
}