In: Computer Science
Method: DoublyLinkedList reverse(DoublyLinkedList list) Reverse() method accepts a DoublyLinkedList of Character as the argument, reverses the elements in the list, and returns the resulting list. For example:
The given list is
'a' 'b' 'c' 'd' 'e'
The return list should be
'e' 'd' 'c' 'b' 'a'
C++ PROGRAM
#include<iostream>
using namespace std;
// create class for Node
class Node
{
public:
// public data members
char data;
Node *next,*prev; // reference pointers
};
// implement insert() function with two parameters
// first parameter is Node pointer object head
// second parameter character arguement
void insert(Node **head,char x)
{
Node *temp=new Node(); // create pointer temp
object
temp->data=x; // assign x value to temp
object
temp->prev=NULL; // assign temp->prev=NULL
temp->next=*head; // assign
temp->next=head
if(*head!=NULL) // check head!=NULL
(*head)->prev=temp; // then, assign
head->prev=temp
*head=temp; // finally assign head=temp
}
// implement display() function with single argument
void display(Node *mynode)
{
Node *last; // declare pointer object last
while(mynode!=NULL) // create while loop mynode is not
null
{
cout<<mynode->data<<" "; // display mynode
data
last=mynode; // assign mynode to
last
mynode=mynode->next; // repeat
mynode->next until NULL
}
}
// implement reverse() function with single argument
// return pointer Node type
Node * reverse(Node *head)
{
if(head==NULL) // check head=NULL
return head; // then, return head node
Node *temp=head->prev; // create pointer temp node and assign
head->prev
while(head) // create while loop until head=NULL
{
head->prev=head->next; // assign head->next
to head->prev
head->next=temp; // assign temp node to
head->next
temp=head; // assign head to temp
head=head->prev; // repeate head->prev until
NULL
}
return temp; // return temp node
}
int main()
{
Node *head=NULL; // create pointer node head and
assign NULL
// calling insert() function and insert values into
head node
insert(&head,'e');
insert(&head,'d');
insert(&head,'c');
insert(&head,'b');
insert(&head,'a');
cout<<"The given list is"<<endl;
display(head); // calling display() function and
display original list
Node *t=reverse(head); // calling reverse() function
and receive return Node list
cout<<"\nThe return list should
be"<<endl;
display(t); // calling display() function and display
reverse order list
return 0;
}
OUTPUT-1
The given list is
a b c d e
The return list should be
e d c b a
OUTPUT-2
If insert two more elements then,
insert(&head,'g');
insert(&head,'f');
insert(&head,'e');
insert(&head,'d');
insert(&head,'c');
insert(&head,'b');
insert(&head,'a');
The given list is
a b c d e f g
The return list should be
g f e d c b a