So i have implemented the following link list, but i just want to know if i can sort the link list. any help?

#include<iostream>
#include"ll.h"
using namespace std;

// PURPOSE: contructor which initializes front and rear to NULL and count                                                                                                                                                                                                                                        
//          to 0                                                                                                                                                                                                                                                                                                 
LL::LL()
{
  front = NULL;
  rear = NULL;
  count = 0;
}

// PURPOSE: destructor which deletes                                                                                                                                                                                                                                                                             
LL::~LL()
{
  destroy();
}
// PURPOSE:Adds a new node to the front of the link list                                                                                                                                                                                                                                                         
// PARAMS:                                                                                                                                                                                                                                                                                                       
// ALGORITHM:If front == null creates the first node, which makes                                                                                                                                                                                                                                                
//           front and rear point to it, else if it its not the first                                                                                                                                                                                                                                            
//           node it creates a node.                                                                                                                                                                                                                                                                             
void LL::addFront(el_t NewNum)
{

  if(front == NULL)//CASE:1(if the list is empty)                                                                                                                                                                                                                                                                
    {
      front = rear = new Node;
      front->elem = NewNum;
    }
  else//CASE:2(if the list is not empty)                                                                                                                                                                                                                                                                         
    {
      Node *x;
      x = new Node;
      x ->next = front;
      front = x;
     front->elem = NewNum;
    }
}

// PURPOSE:adds a new node at the rear and puts data in the                                                                                                                                                                                                                                                      
//         first fielf of this new node                                                                                                                                                                                                                                                                          
// PARAMS:                                                                                                                                                                                                                                                                                                       
// ALGORITHM:If empty,rear is NULL then it will make front and                                                                                                                                                                                                                                                   
//           rear point to a new node, else it will create a new                                                                                                                                                                                                                                                 
//           Node at the end of the list                                                                                                                                                                                                                                                                         
void LL::addRear(el_t NewNum)
{

  if(rear == NULL)//CASE:1(if rear is null)                                                                                                                                                                                                                                                                      
    {
      front = rear = new Node;
      rear->elem = NewNum;
    }
  else//CASE:2(if the list is not empty)                                                                                                                                                                                                                                                                         
    {
      rear->next = new Node;
      rear = rear->next;
      rear->elem = NewNum;
      rear->next = NULL;

    }
  count++;
}

// PURPOSE: IF queue is empty displays the error, else it gives back                                                                                                                                                                                                                                             
//          the front node of the element                                                                                                                                                                                                                                                                        
// PARAMS:                                                                                                                                                                                                                                                                                                       
// ALGORITHM:It checks empty to see if there is any elements, else                                                                                                                                                                                                                                               
//           it will create a second pointer and have it point to the                                                                                                                                                                                                                                            
//           next element and delete the element.                                                                                                                                                                                                                                                                
void LL::deleteFront(el_t& OldNum)
{

  if(isEmpty())//CASE:1(if the list is empty)                                                                                                                                                                                                                                                                    
    {
      cout <<"Cant remove from an empty list";
    }

  else//CASE:2(if the list is not empty)                                                                                                                                                                                                                                                                         
    {
      Node *second;
      second = front->next;
      delete front;
      front = second;
    }
  count--;

}

// PURPOSE:It will delete a node from the rear of the list                                                                                                                                                                                                                                                       
// PARAMS:                                                                                                                                                                                                                                                                                                       
// ALGORITHM:Checks if its empty first, if it is, it will                                                                                                                                                                                                                                                        
//           display error message, else if the count is 1,                                                                                                                                                                                                                                                      
//           a second pointer will point to front and have front                                                                                                                                                                                                                                                 
//           and rear point to NULL, then wil have the element point                                                                                                                                                                                                                                             
//           to the second pointer element, then it will delete the                                                                                                                                                                                                                                              
//           second pointer. ELSE pointer x will point to front, the while                                                                                                                                                                                                                                       
//           i is less then count 2, x will point to the next and the                                                                                                                                                                                                                                            
//           rear will point to the second pointer.                                                                                                                                                                                                                                                              
void LL::deleteRear(el_t& OldNum)
{
  if(isEmpty())//CASE:1(If the list is empty)                                                                                                                                                                                                                                                                    
    cout<<"cant remove from an empty list";
  else if(count == 1)
    {
      Node *second = front;
      front = rear = NULL;
      count = 0;
      el_t elem = second->elem;
      delete second;
    }
  else//CASE:2(If the list is not empty)                                                                                                                                                                                                                                                                         
    {
      Node *x = front;
      for(int i = 0; i < count -2; i++)
        x = x->next;
      Node *second = rear;
      rear = x;
      rear->next = NULL;
      count--;
      el_t elem = second->elem;
      delete second;
    }

}

//PURPOSE: deletes all nodes                                                                                                                                                                                                                                                                                     
//PARAMS:                                                                                                                                                                                                                                                                                                        
//AlGORITHM:creates a second pointer to point to front, while                                                                                                                                                                                                                                                    
//          front is not empty, it will point to the next node                                                                                                                                                                                                                                                   
//          and keep deleting until it is empty                                                                                                                                                                                                                                                                  
void LL::destroy()
{
  Node *second = front;
  while(front!= NULL)
    {
      front = front->next;
      delete second;
      second = front;
    }
}

// PURPOSE:Checks queue to see if elements do not exist                                                                                                                                                                                                                                                          
// PARAMS: returns bool                                                                                                                                                                                                                                                                                          
// ALGORITHM: if front and rear equals NULL it will return                                                                                                                                                                                                                                                       
//            true, else false                                                                                                                                                                                                                                                                                   
bool LL::isEmpty()
{
  if(front && rear == NULL)
    return true;
  else
    return false;

}

// PURPOSE:Displays all the elements of the queue                                                                                                                                                                                                                                                                
// PARAMS: NONE                                                                                                                                                                                                                                                                                                  
// ALGORITHM: it calls is empty, if empty it will display                                                                                                                                                                                                                                                        
//             a message saying the queue is empty if not                                                                                                                                                                                                                                                        
//             while x is not pointing to NULL it will print                                                                                                                                                                                                                                                     
//             all  the results and keep going until it                                                                                                                                                                                                                                                          
//             to NULL                                                                                                                                                                                                                                                                                           
void LL::displayAll()
{
  if(isEmpty())
    {
      cout <<"queue is empty";
    }
  else
    {
  Node *x = front;
  while(x!= NULL)
    {
      cout << x->elem << "\t";
      x = x->next;
    }
  cout << endl;
    }

Dani AI

Generated

Short answer: yes — sort the list, but pick the right algorithm. As already mentioned, copying nodes into a vector and calling std::sort is the quickest to implement and often fastest for small/medium lists (O(n log n) time, O(n) extra memory). For a true linked-list solution (no extra array), use merge sort: it’s O(n log n), stable, and works by only changing next pointers, so it fits singly linked lists perfectly. ’s note about operator overloads is useful when you use STL sorting functions or std::sort on a vector.

Implementation outline (recommended)

  • Split the list into two halves with slow/fast pointers.
  • Recursively sort each half.
  • Merge two sorted halves by relinking nodes (no new allocations).
    This gives O(n log n) time and only O(log n) stack space; for very large lists, use a bottom-up iterative merge to avoid recursion.

Minimal C++ skeleton (adapt to your Node/el_t):

Node* merge(Node* a, Node* b) {
  Node dummy; Node* tail = &dummy; dummy.next = nullptr;
  while (a && b) {
    if (a->elem <= b->elem) { tail->next = a; a = a->next; }
    else { tail->next = b; b = b->next; }
    tail = tail->next;
  }
  tail->next = a ? a : b;
  return dummy.next;
}

Node* mergeSort(Node* head) {
  if (!head || !head->next) return head;
  Node* slow = head; Node* fast = head->next;
  while (fast && fast->next) { slow = slow->next; fast = fast->next->next; }
  Node* mid = slow->next; slow->next = nullptr;
  return merge( mergeSort(head), mergeSort(mid) );
}

Practical cautions for your code before sorting

  • Fix isEmpty() (should test front == NULL, not front && rear == NULL).
  • Always initialize next for new nodes and set rear->next = NULL for the final node.
  • Keep count consistent: increment in addFront/addRear, decrement only when a deletion actually happens.
  • After deletions, if the list becomes empty, set both front and rear to NULL.
  • After sorting, recompute rear (walk to the last node) and ensure count still matches the actual node count.

If you want the simplest route now, copy to std::vector, std::sort with an appropriate comparator (or operator<), then rebuild the list. Otherwise implement the merge functions above and test on small cases first.

Recommended Answers

All 4 Replies

You could do a bubble sort, it's fairly simple, but works in [tex]O(n^2)[/tex].
If I am not wrong, you could also use a quicksort, since it iterates through all the elements in each recurring call anyways. But not the in-place version, since requires random access.

Or you could just copy the whole list into a temporary array, sort it (even using std::sort() from the algorithm header) and then put it back into the list.

You could do a bubble sort, it's fairly simple, but works in [tex]O(n^2[/tex].
If I am not wrong, you could also use a quicksort, since it iterates through all the elements in each recurring call anyways. But not the in-place version, since requires random access.

Or you could just copy the whole list into a temporary array, sort it (even using std::sort() from the algorithm header) and then put it back into the list.

how could i copy it to an array?

Just go from the head to the tail, copying every member inside a vector (sorry, array would work here, but you would have to allocate it dynamically, which is easier with vectors).
Although these causes quite a memory overhead.

An idea that may be viable for you is to define operator overload for > operator for your element type and use STL sorting routines? STL offers most of the popular sorting routines.

see for help

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.