Please don't post code that you've just tossed together. I had to fix up a couple of things before it would even compile.
You never initialize any member variables in LinkedList. This would usually be done with a constructor. Node could benefit from a constructor, too.
It would also be good to have a destructor for LinkedList that deletes the nodes.
You shouldn't need a separate function to insert the first node.
insert_descending should be able to handle that case.
In the print function p should not be initialized to a new Node. It should just be initialized to head.
What you call "last" is usually called "tail" (to go with "head").
Code:
#ifndef LinkedList_h
#define LinkedList_h
#include <iostream>
template <class T>
struct Node
{
T data;
Node<T>* next;
Node(T data, Node<T>* next=nullptr) : data(data), next(next) {}
};
template <class T>
class LinkedList
{
public:
LinkedList() : count(), head(), tail() {}
~LinkedList() { clear(); }
void clear();
void insert_descending(const T& new_item);
void insert_head(const T& new_item);
int size() const { return count; }
template <class T1>
friend std::ostream& operator<<(std::ostream& os, LinkedList<T1>& list);
protected:
int count;
Node<T>* head;
Node<T>* tail;
};
template <class T>
void LinkedList<T>::clear()
{
while (head)
{
Node<T>* to_delete = head;
head = head->next;
delete to_delete;
}
tail = nullptr;
count = 0;
}
template <class T1>
std::ostream& operator<<(std::ostream& os, LinkedList<T1>& list)
{
Node<T1>* p = list.head;
while (p)
{
os << p->data << ' ';
p = p->next;
}
return os;
}
template <class T>
void LinkedList<T>::insert_head(const T& new_item)
{
head = new Node<T>(new_item, head);
if (!tail)
tail = head;
++count;
}
template <class T>void LinkedList<T>::insert_descending(const T& new_item)
{
Node<T>* newNode = new Node<T>(new_item);
Node<T>* prev = nullptr;
Node<T>* node = head;
while (node && node->data > newNode->data)
{
prev = node;
node = node->next;
}
if (prev)
{
prev->next = newNode;
newNode->next = node;
}
else
{
if (head)
newNode->next = head;
else
tail = newNode;
head = newNode;
}
++count;
}
#endif
#include <iostream>
//#include "LINKEDLIST.h"
using namespace std;
int main()
{
LinkedList<int> list;
for(int i = 0; i < 10; i++)
{
int num;
cin >> num;
list.insert_descending(num);
}
cout << "list: " << list << '\n';
cout << "size: " << list.size() << '\n';
}