I'm new to c++. I was studying data structures and came to know Linked Lists Lately.
We had a problem of finding an item stored inside a linked list and here's the code I wrote using Visual Studio to store and find an item. This code gives me a run time error.
1. "Link.h" file
#pragma once
class Link
{
public:
double num;
char nam[20];
Link* next;
Link(double pnum,char pnam[]);
void displayLink();
};
2. "Link.cpp" file
#include "StdAfx.h"
#include "Link.h"
#include<iostream>
#include<cstring>
using namespace std;
Link::Link(double pnum,char pnam[])
{
next = NULL;
num = pnum;
strcpy(nam,pnam);
}
void Link::displayLink()
{
cout<<num<<"\t"<<nam<<endl;
}
3. "LinkList.h" file
#pragma once
#include"Link.h"
class LinkList
{
private:
Link *first;
public:
LinkList();
void insertFirst(double n,char nm[]);
Link* find(double n);
};
4. "Linklist.h" file
#include "StdAfx.h"
#include "LinkList.h"
#include"Link.h"
#include<iostream>
using namespace std;
LinkList::LinkList()
{
first = NULL;
}
void LinkList::insertFirst(double n,char nm[])
{
Link *temp = new Link(n,nm);
temp->next = first;
first = temp;
cout<<"DATA ENTERED"<<endl;
}
Link* LinkList::find(double n)
{
Link *cur = first;
while(cur!=NULL)
{
if(cur->num == n)
{
return cur;
}
else
{
cur = cur->next;
}
}
return NULL;
}
5."LinkList_5.cpp" (main program)
#include "stdafx.h"
#include<iostream>
#include"Link.h"
#include"LinkList.h"
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
LinkList *ne = new LinkList();
ne->insertFirst(12.22,"Charith");
ne->insertFirst(13.22,"Lalitha");
cout<<ne->find(12.22)->num;
system("PAUSE");
return 0;
}
I've doubt about the way I accessed items that're returned by 'find' method. Can somebody please tell me a way of getting out values returned in that particular method inside the LinkList_5.cpp.