Javascript Program For Comparing Two Strings Represented As Linked Lists
Last Updated :
15 Jun, 2022
Given two strings, represented as linked lists (every character is a node in a linked list). Write a function compare() that works similar to strcmp(), i.e., it returns 0 if both strings are the same, 1 if the first linked list is lexicographically greater, and -1 if the second string is lexicographically greater.
Examples:
Input: list1 = g->e->e->k->s->a
list2 = g->e->e->k->s->b
Output: -1
Input: list1 = g->e->e->k->s->a
list2 = g->e->e->k->s
Output: 1
Input: list1 = g->e->e->k->s
list2 = g->e->e->k->s
Output: 0
Javascript
<script>
var head;
var a, b;
class Node
{
constructor(d)
{
this .data = d;
this .next = null ;
}
}
function compare(node1, node2)
{
if (node1 == null &&
node2 == null )
{
return 1;
}
while (node1 != null &&
node2 != null &&
node1.data == node2.data)
{
node1 = node1.next;
node2 = node2.next;
}
if (node1 != null &&
node2 != null )
{
return (node1.data >
node2.data ? 1 : -1);
}
if (node1 != null &&
node2 == null )
{
return 1;
}
if (node1 == null &&
node2 != null )
{
return -1;
}
return 0;
}
var result = null ;
a = new Node( 'g' );
a.next = new Node( 'e' );
a.next.next = new Node( 'e' );
a.next.next.next =
new Node( 'k' );
a.next.next.next.next =
new Node( 's' );
a.next.next.next.next.next =
new Node( 'b' );
b = new Node( 'g' );
b.next = new Node( 'e' );
b.next.next = new Node( 'e' );
b.next.next.next =
new Node( 'k' );
b.next.next.next.next =
new Node( 's' );
b.next.next.next.next.next =
new Node( 'a' );
var value;
value = compare(a, b);
document.write(value);
</script>
|
Output:
1
Time Complexity: O(M + N), where M and N represents the length of the given two linked lists.
Auxiliary Space: O(1), no extra space is required, so it is a constant.
Please refer complete article on Compare two strings represented as linked lists for more details!
Share your thoughts in the comments
Please Login to comment...