Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Program to find the middle node of the linked list in a single traversal
- #include <iostream>
- 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{
- protected:
- node* head;
- public:
- //constructor for the Linked List class
- Linkedlist(){
- head = NULL;
- }
- //method returns true if the list is empty
- bool isEmpty(){
- return head == NULL;
- }
- //returns head node
- node* getHead(){
- return this->head;
- }
- //method to add a node at starting
- void addToStart(int element){
- node* tempNode = new node(element);
- if(head == NULL){
- head = tempNode;
- }
- else{
- tempNode->updateLink(head);
- head = tempNode;
- }
- }
- // method to add a node at the end
- void addToEnd(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;
- }
- int middleNode(){
- node* tempNode = head;
- node* fast = head;
- node* slow = head;
- while(1){
- if(fast->getNextNode() != NULL){
- fast = fast->getNextNode();
- slow = slow->getNextNode();
- }else{
- break;
- }
- if(fast->getNextNode() != NULL){
- fast = fast->getNextNode();
- }else{
- break;
- }
- }
- return slow->getElement();
- }
- };
- int main() {
- Linkedlist l1;
- l1.addToStart(23);
- l1.addToStart(1);
- l1.addToStart(5);
- l1.addToStart(26);
- l1.addToStart(27);
- l1.addToStart(28);
- l1.addToEnd(24);
- l1.addToEnd(22);
- l1.addToEnd(13);
- cout<<"\nThe Elements of the Linked List are : ";
- l1.display();
- cout<<"\n\nMiddle Node of the Linked List is : "<<l1.middleNode();
- return 0;
- }
Add Comment
Please, Sign In to add comment