Singly Linked Lists, contd.

In this post, we will discuss the code for some commonly used functions in linked lists.

Appending data at the tail:

int appendAtTail(int a){
      Node* new_node = new Node();
      new_node->data = a;
      new_node->tail = NULL;
      Node* temp = head;
      while(temp->tail!=NULL)temp = temp->tail;
      temp->tail = new_node;
      return a;
    }

What we do is pretty obvious, we create a new node, assign it the data and its tail as null. Now we create a temp pointer traverse it to the end and when reached the last node, we assign this node's tail the pointer to the new node.
It is clearly a task of O(N) complexity.

At a location in between:

void addAt(int location, int a){
      if(location==0){ // in case the location is zero we append at to the head

        appendathead(a);
        return;

      }else{
        Node* temp = head;
        int x = location-1;
        while(x--){
          if(temp == NULL){
            cout << "Index out of bounds" << '\n';
            return;
          }
          temp = temp->tail;
        } // the code till now was to get the temp to correct previous node location

        Node* new_node = new Node(); // create a new node
        new_node-> data = a;
        new_node-> tail = temp->tail; // first assign the new node the correct tail
        temp->tail = new_node;
      }
    }
I think you should try to understand how this code works, and what it does. I have commented it properly for your help.

No comments:

Post a Comment

Installing albert on ubuntu 19.04

Installing Albert on Ubuntu 19.04... Albert is not still released for ubuntu 19.04. But still, you can install it using the following ...