Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- using namespace std;
- class LinkedList
- {
- private:
- public:
- struct Node // declare the node struct
- {
- int NodeData; // data
- int ID;
- struct Node* NextNode; // location of next node
- };
- struct Node* Head; /* "Head" of list - basically has nothing
- except the location of the next item on the list */
- LinkedList() // constructor initializes head
- {
- Head = new Node;
- Head->NextNode = NULL;
- }
- ~LinkedList() // deconstructor, nothing unusual here
- {
- DeleteAll();
- }
- void AddNodeAtEnd(int NodeData, int ID) /* Adds a new node to the end*/
- { /*of the list with the given input*/
- struct Node* NewNode = new Node; // create new node
- NewNode->NodeData = NodeData; // set data
- NewNode->ID = ID;
- NewNode->NextNode = NULL;
- struct Node* LastNode = NULL;
- if (Head->NextNode == NULL) // check to see if list is empty
- {
- Head->NextNode = NewNode;
- return;
- }
- LastNode = GetLastNode(); // get location of the last node in the list
- LastNode->NextNode = NewNode; // set former last node's address pointer
- }
- Node* GetLastNode() // get the last node's memory location as a pointer
- {
- if (Head->NextNode == NULL) // error checking
- return NULL;
- struct Node *TempNode = Head; // create temp node pointer at the head
- while (TempNode->NextNode != NULL) // cycle through all the elements until there are no more
- TempNode = TempNode->NextNode;
- return TempNode;
- }
- int GetSize() // same as before, but gives the size of the list instead
- {
- if (Head == NULL)
- return 0;
- int Size = 0;
- struct Node *TempNode = Head;
- while (TempNode->NextNode != NULL)
- {
- TempNode = TempNode->NextNode;
- Size++;
- }
- return Size;
- }
- void PrintAll() // same as before, but prints every node's data instead
- {
- if (Head == NULL)
- {
- cout << "Empty!";
- return;
- }
- struct Node* TempNode = Head;
- while (TempNode->NextNode != NULL)
- {
- TempNode = TempNode->NextNode;
- cout << TempNode->NodeData << " " << TempNode->ID << " " /*<< TempNode->NextNode*/ << endl;
- }
- }
- void DeleteAll() // same as before, but deletes every node instead
- {
- if (Head == NULL)
- return;
- struct Node* TempNode = Head;
- struct Node* DeletingThisNode = NULL;
- while (TempNode->NextNode != NULL)
- {
- DeletingThisNode = TempNode;
- TempNode = TempNode->NextNode;
- //cout << TempNode->NodeData << " " << TempNode->ID << " " /*<< TempNode->NextNode*/ << endl; // error checking stuff
- delete DeletingThisNode;
- }
- delete Head;
- Head = NULL;
- }
- };
- int main()
- {
- LinkedList Testing;
- Testing.AddNodeAtEnd(156, 135);
- Testing.AddNodeAtEnd(12, -15);
- Testing.PrintAll();
- cout << endl;
- Testing.DeleteAll();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement