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++; } /**...
// C++ Doubly linked list class clinknode{ friend class DList; public:     clinknode(){next = prev=0;data =0;}...
// C++ Doubly linked list class clinknode{ friend class DList; public:     clinknode(){next = prev=0;data =0;} protected:     clinknode *next;     clinknode *prev;     int data; } class DList{ public: DList(){first = last = 0;} void insertFront(int key); bool found(int key){ return search(key)!=0;} void deleteAll(int key); // other list functions... private: clinknode *search(int); clinknode *first; clinknode *last; } (20 points) Write the code for the deleteAll (int key) member function. It takes a key value and deletes all of the...
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)   ...
Laboratory Tasks public class LinkedList {              Node head;               class Node {    &nbsp
Laboratory Tasks public class LinkedList {              Node head;               class Node {                       int data;                     Node next;                     Node(int d) {                             data = d;                             next = null;                     }                 } } Complete the above java program by adding the following methods: Part1: isEmpty() checks if the linked list is empty or not. (return type is boolean) printList() prints all data in the linked list. (void method) insertFirst(int newData) add newData at the head of the linked list. (void method) insertLasL(int newData) add newData at...
Using Doubly Linked List, create a java code that does the following Without using LinkedList from...
Using Doubly Linked List, create a java code that does the following Without using LinkedList from the JAVA LIBRARY. and please include methods for each function. Create a menu that contains the following operations : 1. Add new node to DLL. ( as a METHOD ) 2. Delete a node from DLL. ( as a METHOD ) 3. Show how many nodes in DLL. ( as a METHOD ) 4. Print all data in the DLL. ( as a METHOD...
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 ==...
Write java code to reverse a linked list. Fill in reverseLists() ReverseLinkedList.java package mid; public class...
Write java code to reverse a linked list. Fill in reverseLists() ReverseLinkedList.java package mid; public class ReverseLinkedList {     private static class ListNode {         int val;         ListNode next;         ListNode() {         }         ListNode(int val) {             this.val = val;         }         ListNode(int val, ListNode next) {             this.val = val;             this.next = next;         }     }     public static void printList(ListNode l1) {         ListNode cur = l1;         while(cur != null) {             System.out.println(cur.val);             cur = cur.next;         }     }     public static ListNode reverseLists(ListNode h1) {     }     public static void...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT