title: How to insert node in sorted doubly linked list at the end?
body: <pre><code>#include &lt;iostream&gt;
  #include &lt;stdlib.h&gt;
  using namespace std;
  struct Node{
      int data;
      Node* next;
      Node* prev;
  };
  Node* head;
  
  void display(){
      Node* temp = head;
      while(temp!=NULL){
          cout&lt;&lt;temp-&gt;data&lt;&lt;&quot; &quot;;
          temp = temp-&gt;next;
      }
      cout&lt;&lt;endl;
  }
  void insert(int value){
      Node* temp = (Node*)malloc(sizeof(Node));
      temp-&gt;data = value;
      temp-&gt;prev = NULL;
      temp-&gt;next = NULL;
      if(head==NULL){
          head = temp;
  
      }
      else{
          Node* t = head;
          while(t-&gt;next!=NULL){
              t = t-&gt;next;
          }
          t-&gt;next = temp;
          temp-&gt;next = NULL;
          temp-&gt;prev = t;
      }
  }
  void insertAtFirst(int value){
      Node* temp = (Node*)malloc(sizeof(Node));
      temp-&gt;data = value;
      temp-&gt;prev = NULL;
      temp-&gt;next = head;
      head-&gt;prev = temp;
      head = temp;
  }
  void sortedInsert(int value){
      Node* curr = head;
      while(curr-&gt;next!=NULL)
          curr = curr-&gt;next;
  
      Node* temp = (Node*)malloc(sizeof(Node));
      temp-&gt;data = value;
      
      if(head==NULL || temp-&gt;data &lt; head-&gt;data){
          temp-&gt;prev = NULL;
          temp-&gt;next = head;
          head-&gt;prev = temp;
          head = temp;
      }
      else if(head-&gt;next!= NULL &amp;&amp; temp-&gt;data &gt;= head-&gt;data){
          Node* pred = head;
          while(temp-&gt;data &gt; pred-&gt;data){
              pred = pred-&gt;next;
          }
          
          pred-&gt;prev-&gt;next = temp;
          temp-&gt;prev = pred-&gt;prev;
          temp-&gt;next = pred;
          pred-&gt;prev = temp;
      }
  
      else if(curr-&gt;next==NULL){
          curr-&gt;next = temp;
          temp-&gt;prev = curr;
          temp-&gt;next = NULL;
      }
  }
  int main()
  {
      insert(10);
      insert(20);
      insert(25);
      insert(35);
      insertAtFirst(1);
      insertAtFirst(29);
      sortedInsert(30);
      sortedInsert(40);
  
      //1 10 20 25 29 30 35 40
      display();
  
  
      return 0;
  }
  </code></pre>
  <p>I think I have implemented the doubly linked list probably. However, the problem I am facing is that when I try to input a node that has a greater data than the existing data of the last node, it doesn't save. There is probably something wrong with the logic I have employed - looked up some previous answers but failed to fix the problem.</p>