linked list not working
Nov 1, 2015 at 10:38am UTC
I just want to make a linked list program that can insert node, delete node, find node and display all the node, but i was not expert in program. i have tried to make a coding based on note, but it does not work. Help me solve this problem please.
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 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
#include <iostream>
using namespace std;
class Node {
public :
double data;
Node *next;
};
class List{
Node* head;
public :
int InsertNode (double x);
int FindNode (double x);
int DeleteNode (double x);
void DisplayList (void );
};
int List::InsertNode(double x) {
int currIndex = 0;
Node* currNode = head;
Node* prevNode = NULL;
while (currNode && x > currNode-> data) {
prevNode = currNode;
currNode = currNode->next;
currIndex++;
}
Node* newNode = new Node;
newNode->data = x;
if (currIndex == 0) {
newNode->next = head;
head = newNode;
}
else {
newNode->next = prevNode->next;
prevNode->next = newNode;
}
return 0;
}
int List::FindNode(double x) {
Node* currNode = head;
int currIndex = 1;
while (currNode && currNode->data != x) {
currNode = currNode->next;
currIndex++;
}
if (currNode)
return currIndex;
else
return 0;
}
int List::DeleteNode(double x) {
Node* prevNode = NULL;
Node* currNode = head;
int currIndex = 1;
while (currNode && currNode->data != x) {
prevNode = currNode;
currNode = currNode->next;
currIndex++;
}
if (currNode) {
if (prevNode) {
prevNode->next = currNode->next;
delete currNode;
}
else {
head = currNode->next;
delete currNode;
}
return currIndex;
}
return 0;
}
void List::DisplayList()
{
int num = 0;
Node* currNode = head;
while (currNode != NULL){
cout << currNode->data << endl;
currNode = currNode->next;
num++;
}
cout << "Number of nodes in the list: " << num << endl;
}
int main(void )
{
//int num;
//cout<<"how many data :";
//cin >>num;
List list;
list.InsertNode(7); // successful
list.InsertNode(5); // successful
list.InsertNode(6); // successful
list.InsertNode(4); // successful // print all the elements
list.DisplayList();
if (list.FindNode(5) > 0) cout << "5 found" << endl;
else
cout << "5 not found" << endl;
if (list.FindNode(4) > 0) cout << "4 found" << endl;
else
cout << "4 not found" << endl;
list.DeleteNode(7);
list.DisplayList();
return 0;
}
Topic archived. No new replies allowed.