# C++ Notes: Data Structures: Lists - Example 1b

Here are the functions that are used by the header file and main program.

      1
      2
      3
      4
      5
      6
      7
      8
      9
     10
     11
     12
     13
     14
     15
     16
     17
     18
     19
     20
     21
     22
     23
     24
     25
     26
     27
     28
     29
     30
     31
     32
     33
     34
     35
     36
     37
     38
     39
     40
     41
     42
     43
     44
     45
     46
     47
     48
     49
     50
     51
     52
     53
     54
     55
     56
     57
     58
     59
     60
     61
     62
    //--- list1/list_node.cpp  -- Fred Swartz 2001-12-13
    #include <iostream>
    using namespace std;

    #include "list_node.h"

    //=============================================== printList
    void printList(ListNode* start) {
        for (; start!=NULL; start=start->next) {
            cout << start->data << " ";
        }
        cout << endl;
    }//end printList

    //============================================ readListLIFO
    ListNode* readListLIFO(istream& input) {
        ListNode* front = NULL;  // first element
        int x;

        while (input >> x) {
            ListNode* newnode = new ListNode();
            newnode->data = x;
            newnode->next = front;  // Points to rest of list

            front = newnode;        // Make this new head
        }
        return front;
    }//end readListLIFO

    //=============================================== readList
    ListNode* readList(istream& input) {
        ListNode* front = NULL;  // first element
        ListNode* back  = NULL;  // last element
        int x;

        while (input >> x) {
            ListNode* newnode = new ListNode();
            newnode->data = x;
            newnode->next = NULL;   // this is the end

            if (front == NULL) {
                front = newnode;    // if this is the first node
                back  = newnode;    // it's both the front and back.
            }else{
                back->next = newnode; // prev end points to newnode
            }
            back = newnode;         // new end of list
        }
        return front;
    }//end readList

    //=============================================== clear
    void clear(ListNode* somelist) {
        ListNode* temp;  // stores next pointer before delete
        for (ListNode* p = somelist; p != NULL; p = temp) {
            temp = p->next;  // must save before delete
            delete p;
        }
    }//end clear