Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

1. Write the method checkListEndsSymmetry that receives a double linked list and

ID: 3598280 • Letter: 1

Question

1. Write the method checkListEndsSymmetry that receives a double linked list and an integer number k. The method checks if the double linked list has identicalk elements going forward from the first element and backwards from the last one. The method returns true if they are identical, and false otherwise. The method signature is: public boolean checkListEndsSymmetry (DoubleLinkedList dl, int k) Example 3.1. If dl = A B C D B A and k = 2, then the method should return true. If k = 3, it should return false, since C does not equal D

Explanation / Answer

// assuming node class

class Node<T>

{

    T data;

    Node<T> next;

    Node<T> prev;

   

    // constructor

    Node(T data)

    {

        this.data = data;

        next = null;

        prev = null;

    }

}

class DoubleLinkedList<T>

{

    // point to the beginning of the list

    Node<T> head;

   

    // point to the last node of the list

    Node<T> tail;

    public boolean checkListEndsSymmetry(DoubleLinkedList<T> dl, int k)

    {

        if( k == 0 )

            return true;

       

        // point to the beginning of the list

        // traverses the list from first node to the last node

        Node<T> front = head;

       

        // point to the last node of the list

        // traverses the list from last node to the first node

        Node<T> back = tail;

       

        // traverse untill the list reches the end

        while(front != null && back != null)

        {

            // if the two nodes are not equal

            if(front.data != back.data)

                return false;

            // if the two nodes are equal

            else

            {

                // decrement k as the two nodes areequal

                k--;

               

                // if the k nodes have been found equal

                if( k == 0 )

                    return true;

                // if symmetry of more nodes need to be checked

                else

                {

                    // make front point to next node

                    front = front.next;

                   

                    // make back point to previous node

                    back = back.prev;

                }

            }

        }

       

        // if the list is not symmetrical

        return false;

    }

   

}