Question

In: Computer Science

Consider the following definition of a doubly linked-list: class LinkedList{ public: LinkedList():head(0), tail(0){} ~LinkedList(); void reverse();...

Consider the following definition of a doubly linked-list:

class LinkedList{
        public:
                LinkedList():head(0), tail(0){}
                ~LinkedList();
                void reverse(); 
                //reverses the order of elements in the linked list
                void insert(int value);
        private:
            struct Node{
                        int data;
                        Node* next;
                        Node* prev;
                };
                Node* head;
                Node* tail;
                //Add your helper function here that recursively reverses the order of elements in the linked list


};

Write the declaration of a helper function in the class provided above that recursively reverses the order of elements in the linked list. This function will be used by the reverse() method. Then, write the implementation of both the reverse() method and the helper function.

Solutions

Expert Solution

// C++ program to reverse the elements of the LinkedList

#include <iostream>

using namespace std;

class LinkedList{

        public:

                LinkedList():head(0), tail(0){} // default contructor to create an empty linked list

                ~LinkedList(); // destructor to delete the elements of the linked list

                void reverse(); //reverses the order of elements in the linked list

                void insert(int value); // insert an element at the end of the linked list

                void print(); // print the elements of the linked list

        private:

            struct Node{

                        int data;

                        Node* next;

                        Node* prev;

                };

                Node* head;

                Node* tail;

                void reverse(Node *node); // helper function to reverse the linked list recursively

};

LinkedList::~LinkedList()

{

       // loop that continues till we reach the end of the linked list

       while(head != NULL)

       {

             Node *temp = head;

             head = head->next;

             delete(temp); // delete the previous head element

       }

       tail = NULL; // set tail to NULL

}

void LinkedList::insert(int value)

{

       Node *node = new Node;

       node->data = value;

       node->prev = NULL;

       node->next = NULL;

       if(head == NULL) // empty list, insert the value at the front

       {

             head = node;

             tail = node;

       }else // insert the value at the end

       {

             tail->next = node;

             node->prev = tail;

             tail = node;

       }

}

void LinkedList::print()

{

       if(head == NULL) // empty list

       {

             cout<<"Empty list"<<endl;

       }else

       {

             Node *curr = head;

             // loop to print the elements of the linked list

             while(curr != NULL)

             {

                    cout<<curr->data<<" ";

                    curr = curr->next;

             }

             cout<<endl;

       }

}

void LinkedList::reverse()

{

       reverse(head); // call the helper function

       // swap head and tail

       Node *temp = head;

       head = tail;

       tail = temp;

}

void LinkedList::reverse(Node *node)

{

       if(node != NULL) // if node is not null

       {

             // swap the next and prev pointers of the node

             Node *temp = node->next;

             node->next = node->prev;

             node->prev = temp;

             reverse(node->prev); // call the helper function to reverse the previous node

       }

}

int main() {

       // test the functions of the LinkedList class

       LinkedList list;

       // insert elements to list

       for(int i=1;i<=10;i++)

             list.insert(i);

       cout<<"Original List : "<<endl;

       list.print(); // print the original list

       // reverse the list

       list.reverse();

       // print the reversed list

       cout<<"Reversed List : "<<endl;

       list.print();

       return 0;

}

//end of program

Output:


Related Solutions

Author code /** * LinkedList class implements a doubly-linked list. */ public class MyLinkedList<AnyType> implements Iterable<AnyType>...
Author code /** * LinkedList class implements a doubly-linked list. */ public class MyLinkedList<AnyType> implements Iterable<AnyType> { /** * Construct an empty LinkedList. */ public MyLinkedList( ) { doClear( ); } private void clear( ) { doClear( ); } /** * Change the size of this collection to zero. */ public void doClear( ) { beginMarker = new Node<>( null, null, null ); endMarker = new Node<>( null, beginMarker, null ); beginMarker.next = endMarker; theSize = 0; modCount++; } /**...
Remove the minimum element from the linked list in Java public class LinkedList {      ...
Remove the minimum element from the linked list in Java public class LinkedList {       // The LinkedList Node class    private class Node{               int data;        Node next;               Node(int gdata)        {            this.data = gdata;            this.next = null;        }           }       // The LinkedList fields    Node head;       // Constructor    LinkedList(int gdata)   ...
import java.util.LinkedList; public class StudentLinkedList { public static void main(String[] args) { LinkedList<Student> linkedlist = new...
import java.util.LinkedList; public class StudentLinkedList { public static void main(String[] args) { LinkedList<Student> linkedlist = new LinkedList<Student>(); linkedlist.add(new Student("Ahmed Ali", 20111021, 18, 38, 38)); linkedlist.add(new Student("Sami Kamal", 20121021, 17, 39, 35)); linkedlist.add(new Student("Salem Salim", 20131021, 20, 40, 40)); linkedlist.add(new Student("Rami Mohammed", 20111031, 15, 35, 30)); linkedlist.add(new Student("Kim Joe", 20121024, 12, 32, 32)); linkedlist.addFirst(new Student("Hadi Ali", 20111025, 19, 38, 39)); linkedlist.addLast(new Student("Waleed Salim", 20131025, 10, 30, 30)); linkedlist.set(0, new Student("Khalid Ali", 20111027, 15, 30, 30)); linkedlist.removeFirst(); linkedlist.removeLast(); linkedlist.add(0, new Student("John Don",...
class ArrayReverse1{ public static void reverse(int[] a, int index) { if (index >0) { index= index...
class ArrayReverse1{ public static void reverse(int[] a, int index) { if (index >0) { index= index - 1; // Decrementing the index System.out.printf("%d%n", a[index]); reverse(a, index); // Recursive call } return; } public static void main (String args[]) { int [] array = { 1, 2, 3, 4, 5 }; int n=array.length; reverse(array,n); // function call } } Write a generic version of the corrected recursive reverse method that could be used to print any of the following arrays (or...
Python class DLLNode: """ Class representing a node in the doubly linked list implemented below. """...
Python class DLLNode: """ Class representing a node in the doubly linked list implemented below. """ def __init__(self, value, next=None, prev=None): """ Constructor @attribute value: the value to give this node @attribute next: the next node for this node @attribute prev: the previous node for this node """ self.__next = next self.__prev = prev self.__value = value def __repr__(self): return str(self.__value) def __str__(self): return str(self.__value) def get_value(self): """ Getter for value :return: the value of the node """ return self.__value...
Remove the Head element from the code below: public class LinkedList {    class Node{ int...
Remove the Head element from the code below: public class LinkedList {    class Node{ int value; Node nextElement; public Node(int value) { this.value = value; this.nextElement = null; } } public Node first = null; public Node last = null; public void addNewNode(int element) { Node newValueNode = new Node(element);    if(first == null) { first = newValueNode; } else { last.nextElement = newValueNode; } last = newValueNode; } public void displayValues() { Node recent = first; if(first ==...
Java program to implement circular linked list. public class CircularLinkedList { private Node tail; private int...
Java program to implement circular linked list. public class CircularLinkedList { private Node tail; private int size; public CircularLinkedList() { tail= null; size = 0; } public int size(){ return size; } public boolean isEmpty() { return size==0; } //if list is not empty return the first element public E first() { if (isEmpty()) return null; //code here return 0; } //if list not empty return last element public E last() { if (isEmpty()) return null; return tail.getElement(); } /*...
Study the following class definition: class Car { public: Car(double speed); void start(); void accelerate(double speed);...
Study the following class definition: class Car { public: Car(double speed); void start(); void accelerate(double speed); void stop(); double get_speed() const; private: double speed; }; Which of the following options would make logical sense in the definition of the void accelerate(double speed)function? Group of answer choices this->speed = this->speed; this->speed = speed; this.speed = speed; speed1 = this->speed; Flag this Question Question 131 pts The Point class has a public function called display_point(). What is the correct way of calling...
Write in C++: create a Doubly Linked List class that holds a struct with an integer...
Write in C++: create a Doubly Linked List class that holds a struct with an integer and a string. It must have append, insert, remove, find, and clear.
Using the singly linked list code as a base, create a class that implements a doubly...
Using the singly linked list code as a base, create a class that implements a doubly linked list. A doubly linked list has a Previous link so you can move backwards in the list. Be sure the class is a template class so the user can create a list with any data type. Be sure to test all the member functions in your test program. c++
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT