-
Linked lists
I need some help, ive been trying for a few days to make a linked list, but it keeps on crashing, or not working at all. its kind of wierd though, I can do opengl, but cant make a linked list :P
Code:
#include <stdio.h>
#include <iostream>
using namespace std;
class PATIENT
{
public:
char Name[10];
char Gender;
int Age;
char Insurance;
char Insurance_Name[24];
PATIENT* pNext;
};
PATIENT* head;
void AddPatient(PATIENT* pND)
{
pND->pNext = NULL;
PATIENT* head;
if (head=0)
{
head = pND;
return ;
}
PATIENT* current = head;
while (current->pNext)
{
current = current->pNext;
}
current->pNext = pND;
}
void PrintList(PATIENT* head)
{
while(head != NULL)
{
cout << head;
}
}
int main()
{
PATIENT* pND;
cout <<" enter patient name : ";
cin >> pND->Name;
cout<<"\n\n";
AddPatient(pND);
whats the matter with it, and can someone give a link to a site that has a good tutorial on linked lists, as all the books I have barely skim the topic.
-
The code is somewhat mixed up, but I have some general hints:
seperate data and linked list code. Make a data class and a linked list class. Don't mix it. If you have pointers, make sure you actually have an object assigned with new.
-
Code:
PATIENT* pND;
cin >> pND->Name;
You have a pointer to a patient - true, but it doesn't point at a patient. You need to allocate memory for it.
Also, in your Addpatient you might want to traverse to the end of the list before inserting it. I see some attempt at that but generally your insertion function is pretty screwed.
Why nullify it? You'll cut the list doing so, making the tail lost forever (don't count on windows handling that memory leak for ya :)).
Code:
PATIENT* head;
if (head=0)
My poor eyes... :(
First, you never allocate memory for it, second = is the assignment operator, not a comparator. Third, I'd use NULL instead of 0, but that's my taste (I know others who would argue the opposite, but let's hope they never find this thread :p).
-
yes, I knopw, rather crappy attempt, but its only my first. Do you know where I could find an indepth tutorial to linked lists?
-
-
You have a local variable named head that "shadows" the global varable named head . With a singlely linked list life is much easyer if you "push" elements on the head of your list, so the list will be in reverse order.
Code:
patent *head = 0;
void push(patent *p) {
if(p) {
p->pNext = head;
head = p;
} else {
std::cerr << "NULL patent \n";
}
}