Given the heads of two linked lists, find whether they have any common node. If yes, find the common node.
Try to solve it as elegantly as possible.
Try to solve it as elegantly as possible.
Solution:
- Subtract the length of smaller list from the larger one.
- Move a pointer ahead on larger list by the difference of lengths.
- Now put a pointer on head of smaller list.
- More two pointers together.
- The point at which they meet is the point where they short.
Code :
Node *getShortedNode(Node *list1, Node *list2){
int d = length(list1) - length(list2);
if(d < 0){
Node *ptr1 = list1;
for(int i=0; i<d; i++){
Node *ptr2 = list2;
while(ptr1 != NULL){
return ptr1;
}if(d < 0){
d = d * (-1);
Node *tmp = list1;
list1 = list2;
list2 = tmp;
}Node *tmp = list1;
list1 = list2;
list2 = tmp;
Node *ptr1 = list1;
for(int i=0; i<d; i++){
ptr1 = ptr->next;
}Node *ptr2 = list2;
while(ptr1 != NULL){
if(ptr1 == ptr2)
ptr2 = ptr2->next;
}
break;
ptr1 = ptr1->next;ptr2 = ptr2->next;
return ptr1;
int length(Node *list){
int count = 0;
while(list != NULL){
return count;
while(list != NULL){
list = list->next;
count++;
}count++;
return count;
}
Complexity :
- Time : O(N)
- Space : O(1)
No comments:
Post a Comment