Which are the best logical steps to code an isSublist(..). method that receives a linked list as parameter called plist and determine if all the elements are present in the calling list straight after each other. Ex.
[1,2,3,4,5,6] [2,3,4] true [2,4,5] false.
import java.util.*;
class Main
{
static class Node
{
int info;
Node N;
};
static boolean getlist(Node top,
Node sec)
{
Node ptr1 = top, ptr2 = sec;
if (top == null && sec == null)
return true;
if (top == null ||
(top != null && sec == null))
return false;
while (sec != null)
{
ptr2 = sec;
while (ptr1 != null)
{
if (ptr2 == null)
return false;
else if (ptr1.info == ptr2.info)
{
ptr1 = ptr1.N;
ptr2 = ptr2.N;
}
else break;
}
if (ptr1 == null)
return true;
ptr1 = top;
sec = sec.N;
}
return false;
}
static void DisplayList(Node node)
{
while (node != null)
{
System.out.printf("%d ", node.info);
node = node.N;
}
}
static Node newNode(int K)
{
Node temp = new Node();
temp.info= K;
temp.N = null;
return temp;
}
public static void main(String[] args)
{ //first list
Node b = newNode(1);
b.N = newNode(2);
b.N.N = newNode(1);
b.N.N.N = newNode(2);
b.N.N.N.N = newNode(3);
b.N.N.N.N.N = newNode(4);
//secondlist
Node a = newNode(1);
a.N = newNode(2);
a.N.N = newNode(3);
a.N.N.N = newNode(4);
if(getlist(a, b) == true)
System.out.println("True");
else
System.out.println("False");
}
}
Comments
Leave a comment