Sort Linked List then print

Discussion in 'C++' started by lastpeony, Oct 15, 2017.

  1. lastpeony

    lastpeony New Member

    Joined:
    Oct 14, 2017
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    1
    I have a linked list with string and int content.i can do operations on it like deleting,adding updating or printing etc.. the problem is i need to print them with respect to their numbers in descending order. Right now im adding new nodes to end of list so it prints old to new.

    Should i sort them while adding or printing ? i guess i should sort them in adding function.i added comments possible place to do sorting.code is below
    Code:
    //list.h content
    struct node{
       
           std::string  data;
           int point;
           node* next;
       
       };
    
       typedef struct node* nodePtr;
       
       nodePtr head;
       nodePtr curr;
       nodePtr temp;
       
       
       // addnode function
       void list::AddNode(string addData,int addPoint){
    
       nodePtr n = new node; //nodePtr is node*
       n->next=NULL; //find node n is pointing to, access its next element make it point to null
       n->data= addData;
       n->point= addPoint;
       if(head != NULL) { // if we have at least 1 element in the list .
       curr = head; // take the current pointer we are working with and make it same with head pointer pointing to.(current= front of list).
       while(curr->next !=NULL){ // are we at the end of the list.
       curr = curr->next;//we are not end of the list.curr pointer points next node. should i do sorting here ?
       }
       curr->next = n;
       
       }else{ //if we dont have at least 1 element in the list.
       
           head =n;
    
       
       }
    
    }
    
    //print function
    void list::PrintList(){
    
       curr = head;
       while(curr !=NULL){
       
           cout<<curr->data<<" "<<curr->point<<endl;
           curr = curr->next;
       
       }
    
    }
    
     
  2. shabbir

    shabbir Administrator Staff Member

    Joined:
    Jul 12, 2004
    Messages:
    15,337
    Likes Received:
    377
    Trophy Points:
    83

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice