Correctly implementing a singly linked list C++

后端 未结 4 776
無奈伤痛
無奈伤痛 2021-01-26 09:34

I have a list with names of employers such as:

Node 1: Jill, Matt, Joe, Bob, Matt

Node 2: Jeff, James, John, J

4条回答
  •  闹比i
    闹比i (楼主)
    2021-01-26 10:23

    I've added a find function

    typedef struct node{
      string data;
      struct node *net, *prev;
     }node;      
    
    
    class list {
    public:
        list():head(NULL), N(0){}
        ~list(){
        //Implementation for cleanup
         }
    
    void add(string name){  //rather than accessing the global data, use the value passed
        node* p = new node(name);
        p->next=p->prev=NULL;
        node* pp = find(name);
        if(pp==NULL){
          // No match found, append to rear
          if(head==NULL)
            head=p;  //list empty, add first element
          else{
            node* cur=head;
            while(cur->next!=NULL) //Keep looking until a slot is found
              cur=cur->next;
            cur->next=p;
            p->prev=cur;
          }
        }
        else{
            //Match found, detach it from its location
            node* pPrev = pp->prev;
            pPrev->next = pp->next;
            pp->next->prev=pPrev;
            p->next = head; //append it to the front & adjust pointers
            head->prev=p;
        }
        N++;
        }
    
        //MER: finds a matching element and returns the node otherwise returns NULL
        node* find(string name){
            node *cur=head;
            if(cur==NULL) // is it a blank list?
              return NULL;
            else if(cur->data==head) //is first element the same?
              return head;
            else   // Keep looking until the list ends
              while(cur->next!=NULL){
              if(cur->data==name)
                return cur;
                cur=cur->next;
              }
            return NULL;
    }
    friend ostream& operator << (ostream& os, const list& mylist);
    
    private:
        int N;
        node *head;
    
    };
    

    Now some may tell you to use the list in STL n never to write your own code coz you can't beat STL, but to me it's good that you are implementing your own to get a clear idea on how it works in reality.

提交回复
热议问题