Linked List Data Structure For BTech
Linked List Data Structure For BTech
Node structure
Each node contains the link to the next node and some data variables.
Implementation
1. Make a node named head. This will act as the start of the linked
list.
To INSERT at the end of the Linked List, iterate to the last node. In the
below code temp is the last node. So temp -> next = new node(val).
Try yourself:
Do a Linear Search in the Linked List.
3. Recursive
Idea: We are at the head, recursively reverse the remaining list.
The (head->next) is the next node, this node should be the
second last node in the reversed list. head would be the last node
in the reversed list, so its next should be NULL. And then we will
return the reversed list.
K REVERSE [IMP]
Given a linked list and an integer K. Reverse the nodes of a linked list k
at a time and return its modified list. If the number of nodes is not a
multiple of K then left-out nodes, in the end, should remain as it is.
Idea: There are 2 cases:
1. The size of the linked list is less than K. In this case, return the list
as it is.
2. The size of the linked list is more than K. Reverse the first K nodes
and recurse for the remaining list.
if(fast->next!=NULL){
slow=slow->next;
}
return slow;
}
REMOVE LOOP IN LINKED LIST
void removeLoop(Node* head)
{
// code here
// just remove the loop without losing any nodes
Node* dummy=new Node(0);
dummy->next=head;
Node* slow=dummy;
Node* fast=dummy;
Node*temp = dummy;
if(slow!=fast) return;
while(temp->next != fast->next)
{
temp = temp ->next;
fast = fast->next;
}
fast ->next = NULL;
head = dummy->next;
}