Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<iostream>
- #include "list.h"
- using namespace std;
- void List::appendNode(int num)
- {
- ListNode *newNode; //Points to new node
- ListNode *nodePtr; //Moves through the list
- //Allocates new node and stores num there:
- newNode = new ListNode;
- newNode->value = num;
- newNode->next = 0;
- //If there are no nodes in the list make newNode the first node:
- if (!head)
- head = newNode;
- else //Else insert newNode at the end:
- {
- nodePtr = head; //Initializes nodePtr to head of the list
- while (nodePtr->next) //Finds the last node in the list
- nodePtr = nodePtr->next;
- nodePtr->next = newNode; //Inserts newNode as the last node
- }
- }
- void List::insertNode(int num)
- {
- ListNode *newNode; //Creates a new node
- ListNode *nodePtr; //To traverse the list
- ListNode *previousNode = 0; //The previous node
- //Allocates a new node and stores num there:
- newNode = new ListNode;
- newNode->value = num;
- //If there are no nodes in the list make newNode the first node
- if(!head)
- {
- head = newNode;
- newNode->next = 0;
- }
- else
- {
- nodePtr = head; //Position nodePtr at the head of the list
- previousNode = 0;
- //Skip all nodes whose value is less than num
- while (nodePtr != 0 && nodePtr->value < num)
- {
- previousNode = nodePtr;
- nodePtr = nodePtr->next;
- }
- //If the new node is the 1st in the list insert it before other nodes
- if (previousNode == 0)
- {
- head = newNode;
- newNode->next = nodePtr;
- }
- else
- {
- previousNode->next = newNode;
- newNode->next = nodePtr;
- }
- }
- }
- void List::deleteNode(int num)
- {
- ListNode *nodePtr;
- ListNode *previousNode;
- //If the list is empty, do nothing:
- if (!head)
- return;
- //Determine if the first node is the one:
- if (head->value == num)
- {
- nodePtr = head->next;
- delete head;
- head = nodePtr;
- }
- else
- {
- nodePtr = head;
- //Skips all nodes whose value member is not equal to num:
- while (nodePtr != 0 && nodePtr->value != num)
- {
- previousNode = nodePtr;
- nodePtr = nodePtr->next;
- }
- //If nodePtr is not at the end of the list link the previous node to the node after nodePtr, then delete nodePtr:
- if (nodePtr)
- {
- previousNode->next = nodePtr->next;
- delete nodePtr;
- }
- }
- }
- void List::displayList()
- {
- ListNode *nodePtr = head;
- while(nodePtr != 0)
- {
- cout << nodePtr->value;
- if (nodePtr->next != 0)
- cout << "-->";
- nodePtr = nodePtr->next;
- }
- }
- List::~List()
- {
- ListNode *nodePtr;
- ListNode *nextNode;
- //Position nodePtr at the head of the list
- nodePtr = head;
- //While nodePtr is not at the end of the list
- while (nodePtr != 0)
- {
- //Save a pointer to the next node
- nextNode = nodePtr->next;
- //Delete the current node
- delete nodePtr;
- //Position nodePtr at the next node
- nodePtr = nextNode;
- }
- }
Add Comment
Please, Sign In to add comment