Showing posts with label Linked List. Show all posts
Showing posts with label Linked List. Show all posts
Sunday, April 21, 2019
Friday, April 19, 2019
Find First Element of Loop in Linked List
C++ Code:
void find_loop_beginning(Node *head){
Node *slow = head;
Node *fast = head;
if (!head || !(head->next))
return;
while(slow && fast && fast->next){
slow = slow->next;
fast = fast->next->next;
if(slow == fast)
break;
}
// No Loop exixts
if (slow != fast){
std::cout << "No Loop" << std::endl;
return;
}
// When Loop exists
slow = head;
while(slow != fast){
slow = slow->next;
fast = fast->next;
}
std::cout << "First loop element = " << slow->data << std::endl;
}
Detailed explanation can be found on Youtube:
Subscribe to KnowledgeCenter
Find k-th node from end in Linked List
void print_kth_from_end(Node *head, int k){
Node *lead = head;
Node *lag = head;
while(k > 0){
if(lead){
k--;
lead = lead->next;
}
else{
std::cout << "K is larger than length of Linked List" << std::endl;
return;
}
}
while(lead){
lead = lead->next;
lag = lag->next;
}
std::cout << "kth node from end = " << lag->data << std::endl;
}
Detailed explanation can be found on Youtube:
Subscribe to KnowledgeCenter
Thursday, April 18, 2019
Find the middle element of a Linked List
void print_middle(Node *head){
Node *fast = head;
Node *slow = head;
while(fast && fast->next){
fast = fast->next->next;
slow = slow->next;
}
std::cout << slow->data << std::endl;
}
Watch the detailed explanation of the concepts on Youtube:
Saturday, April 13, 2019
Detect Loop in a Linked List
Method 1: (Hashing)
bool detect_loop_map(Node *head){
std::unordered_map<Node*, bool> visited;
Node *curr = head;
while(curr){
if (visited[curr] == true)
return true;
visited[curr] = true;
curr = curr->next;
}
return false;
}
Method 2:(Floyd's Cycle Detection)
bool detect_loop_floyd(Node *head){
Node *slow = head;
Node *fast = head;
while(slow && fast && fast->next){
slow = slow->next;
fast = fast->next->next;
if (slow == fast){
return true;
}
}
return false;
}
Watch detailed explanation on Youtube:
Watch detailed explanation on Youtube:
Visit our Youtube playlist for Linked List: https://www.youtube.com/playlist?list=PL1w8k37X_6L-bwZCPpELH6Cwo3WzUxDp7
Subscribe to KnowledgeCenter
Subscribe to KnowledgeCenter
Subscribe to:
Posts (Atom)
LeetCode 30 Day Challenge | Day 7 | Counting Elements
Given an integer array arr , count element x such that x + 1 is also in arr . If there're duplicates in arr , count them sepe...
-
Features of Load Balancer: Distribute load/requests across multiple resources/servers. Keep track of status of all resources while di...
-
Method 1: (Hashing) bool detect_loop_map( Node *head){ std :: unordered_map < Node *, bool > visited; ...
-
Characteristics: No Supervisor, Reward signal Delayed Feedback Data depends on Agent's actions Examples...






