1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

linked list in C

Discussion in 'C' started by mi_sah@yahoo.co.in, Mar 4, 2011.

  1. mi_sah@yahoo.co.in

    mi_sah@yahoo.co.in New Member

    Joined:
    Mar 3, 2011
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    hello everybody.. I need a simple linked list coding in C. Can u help me?.
    Thankx
     
  2. shabbir

    shabbir Administrator Staff Member

    Joined:
    Jul 12, 2004
    Messages:
    15,287
    Likes Received:
    364
    Trophy Points:
    83
  3. bglanzer

    bglanzer New Member

    Joined:
    Mar 2, 2011
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    Here is a simple overview of linked list I will just cover some of the basics.

    Code:
     
    template<typename nodeType>
    class List
    {
    public:
         List();
         ~List();
     
         void PushFront(const nodeType&);
         void PushBack(const nodeType&);
         void PopFront();
         void PopBack();
         void Clear();
    private:
         Node<nodeType> *pHead;  //Always points to the first node
         Node<nodeType> *pTail;   //Always points to the last node
    };
     
    template<typename nodeType>
    List::List():pHead(0),pTail(0){}
     
    template<typename nodeType>
    List::~List()
    {
         Clear();
    }
     
    template<typename nodeType>
    void List::PushFront(const nodeType &node)
    {
        Node<nodeType> *nodePtr=new Node<nodeType>(node);
     
        if(isEmpty())
           pHead=pTail=nodePtr;
        else
         {
               nodePtr->pNext=pHead;
               pHead=nodePtr;
          }
    }
     
    template<typename nodeType>
    void List::PopFront()
    {
        Node<nodeType> *nodePtr=pHead;
        pHead=pHead->pNext;
     
        delete nodePtr;
    }
     
    template<typename nodeType>
    void List::Clear()
    {
       Node<nodeType> *nodePtr;
     
       while(pHead!=pTail)
        {
             nodePtr=pHead;
             pHead=pHead->pNext;
     
             delete nodePtr;
        }
        //delete tail
       delete pHead;
       pHead=0;
       pTail=0;
    }
    
    PushBack and PopBack should be pretty simple a node is simply something as simple as this

    Code:
     
    template <typename type>
    class Node
    {
    public:
       Node();
       ~Node();
     
       Node<type> *pNext;
       Node<type> *pPrev;
    };
    
    I hope that this helps

    Brendon Glanzer
    UAT student
     

Share This Page