Answer to Question #258863 in Java | JSP | JSF for masedi moncho

Question #258863

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.

1
Expert's answer
2021-10-31T12:01:25-0400
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");
}
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS