Linked List

  1. Consider the following code, which created a linked list with 5 elements, and printed out the list sequentially:
    
    #include <iostream>
    using std::cout;
    using std::endl;
    
    struct ListElement
    {
            int value;              // value of an element
            ListElement* pNext;     // Pointer to a list element
    };
    
    void printList(ListElement* p);
    
    int main()
    {
        ListElement LE5 = { 5, NULL };
        ListElement LE4 = { 4, &LE5 };
        ListElement LE3 = { 3, &LE4 };
        ListElement LE2 = { 2, &LE3 };
        ListElement LE1 = { 1, &LE2 };
        printList(&LE1);
        return 0;
    }
    
    void printList(ListElement* p)
    {
        while (p != NULL)
        {
            std::cout << p->value;
            p = p->pNext;
        }
        cout << endl;
    }
    
    
  2. Because we shall repeatedly add new element to the list, it will be useful to create a function to handle this operation:
    
    #include <iostream>
    using std::cout;
    using std::endl;
    
    struct ListElement
    {
            int value;              // value of an element
            ListElement* pNext;     // Pointer to a list element
    };
    
    ListElement* addFront(ListElement* pList, int v);
    
    void printList(ListElement* p);
    
    int main()
    {
        ListElement* pList; 
        pList = addFront(NULL, 5);
        pList = addFront(pList, 4);
        pList = addFront(pList, 3);
        pList = addFront(pList, 2);
        pList = addFront(pList, 1); 
        printList(pList);
        return 0;
    }
    
    void printList(ListElement* p)
    {
        while (p != NULL)
        {
            std::cout << p->value;
            p = p->pNext;
        }
        cout << endl;
    }
    
    ListElement* addFront(ListElement* pList, int v)
    {
        ListElement* p = new ListElement;
        p->pNext = pList;
        p->value = v;
        return p;
    } 
    
    
  3. Modify the main program so that it will use a while loop to read infinite number of integers and create a linked list accordingly. The loop stops when the input integer is less than or equal to zero.

The program may run as follows:

1
2
3
4
5
6
7
0
7654321