/***************************************************************
* Name: Prof. Rafael Orta
* Course: Computer Science & Programming
* Class: CS04225
*****************************************************************
* Purpose: Demonstrate Linked List implementatioin and insertion
* using C++
*****************************************************************/
#include <iostream>
using namespace std;
struct Node {
int data;
struct Node *next;
};
struct Node* head = NULL;
void insert(int);
void display();
int main() {
insert(3);
insert(1);
insert(7);
insert(2);
insert(9);
cout<<"The linked list is: " << endl << endl;
display();
return 0;
}
void insert(int new_data) { // Inserting at the begining of the linked list
Node* new_node = new Node; // Creating a new node in the heap memory.
new_node->data = new_data; // Filling up the data portion with the value passed to the function.
new_node->next = head; // Now next points to the head
head = new_node; // The head gets to be the new node.
}
void display() {
struct Node* ptr; // Creates a pointer namned ptr of type Node.
ptr = head; // Pointes the pointer to point to the address of the head.
cout << " ------- ------- ------ ------ ------ ------ -------" << endl;
cout << "| HEAD | ->" ;
while (ptr != NULL) { // If ptr is NULL we reached the end of the list, the tail is always NULL.
cout<< " | " << ptr->data <<" | -> ";
ptr = ptr->next;
}
cout << "| NULL |" << endl;
cout << " ------- ------- ------ ------ ------ ------ -------" << endl;
}