Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // program to reverse a Linked list
- #include <iostream>
- #include <stack>
- using namespace std;
- class node{
- protected:
- int element;
- node* link;
- public:
- //constructor that accepts only element
- node(int element) {
- this->element = element;
- this->link = NULL;
- }
- //constructor that accepts both link and element
- node(int element, node* link){
- this->element = element;
- this->link = link;
- }
- //method to update the element
- void updateData(int element){
- this->element = element;
- }
- //method to update or setup link
- void updateLink(node* link){
- this->link = link;
- }
- //method to get the element from the node
- int getElement(){
- return this->element;
- }
- //method to get the next node
- node* getNextNode(){
- return this->link;
- }
- };
- class Linkedlist {
- public:
- node *head;
- //constructor for the Linked List class
- Linkedlist() {
- head = NULL;
- }
- //returns head node
- node *getHead() {
- return this->head;
- }
- // method to add a node at the end
- void insert(int element) {
- node *tempNode = new node(element);
- node *p = head;
- if (head == NULL) {
- head = tempNode;
- return;
- }
- else {
- while (p->getNextNode() != NULL) {
- p = p->getNextNode();
- }
- p->updateLink(tempNode);
- return;
- }
- }
- //method to display all the elements of the Linked List
- void display() {
- cout << "\n";
- node *tempNode = head;
- while (tempNode != NULL) {
- if (tempNode->getNextNode() != NULL)
- cout << tempNode->getElement() << " --> ";
- else
- cout << tempNode->getElement();
- tempNode = tempNode->getNextNode();
- }
- return;
- }
- };
- // function to reverse linked list
- node* reverse(node* head){
- if(head == NULL){
- return head;
- }
- node* next = NULL;
- node* prev = NULL;
- node* current = head;
- while(current != NULL){
- next = current->getNextNode();
- current->updateLink(prev);
- prev = current;
- current = next;
- }
- return prev;
- }
- int main() {
- Linkedlist l1;
- l1.insert(1);
- l1.insert(2);
- l1.insert(3);
- l1.insert(4);
- l1.insert(5);
- l1.insert(6);
- l1.insert(7);
- l1.insert(8);
- cout<<"\nBefore Reversing the linked list is : ";
- l1.display();
- l1.head = reverse(l1.head);
- cout<<"\nAfter Reversing the linked list is : ";
- l1.display();
- return 0;
- }
Add Comment
Please, Sign In to add comment