Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #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;
- }
- // rotate a linked list
- // function removes nodes from the beginning and puts them to the end of the linked list;
- void rotate(int shiftValue){
- node* current = this->getHead();
- node* tail = this->getHead();
- // make tail point the last element
- while(tail->getNextNode() != NULL){
- tail = tail->getNextNode();
- }
- for(int i = 0; i < shiftValue; i++){
- tail->updateLink(current);
- current = current->getNextNode();
- tail = tail->getNextNode();
- tail->updateLink(NULL);
- }
- // let head point to the new head node
- this->head = current;
- return;
- }
- };
- int main() {
- cout<<"Program to rotate the Linked List";
- Linkedlist l1;
- l1.insert(1);
- l1.insert(3);
- l1.insert(5);
- l1.insert(7);
- l1.insert(9);
- l1.insert(11);
- l1.insert(13);
- l1.insert(15);
- cout<<"\nBefore rotating the Linked list is : ";
- l1.display();
- cout<<"\nRotating the Linked List by 4 places";
- l1.rotate(4);
- cout<<"\nAfter rotating the Linked List is : ";
- l1.display();
- return 0;
- }
Add Comment
Please, Sign In to add comment