Linked List - Inserting In Order
so far my code is as below. I need to insert records in order and I'm not sure how to.
The program contains pre-defined data which is inserted when the program runs, but it also accepts user input which needs to put in order according to the student number.
thanks
PHP Code:
#include <iostream>
#include <string>
#include <stdlib.h>
struct link {
int stnum;
string name;
link *next;
};
class linklist {
private:
link *first;
public:
linklist() {
first = NULL;
}
void additem(int s, string n);
void display();
void insertitem(int s, string n);
};
void linklist::additem(int s,string n) {
link * newlink = new link;
newlink -> stnum = s;
newlink -> name = n;
newlink -> next = first;
first = newlink;
}
void linklist::insertitem(int s,string n) {
link * newlink = new link;
newlink -> stnum = s;
newlink -> name = n;
newlink -> next = first;
first = newlink;
}
void linklist::display() {
link *current = first;
while(current != NULL) {
cout << current->stnum << " " << current->name <<endl;
current = current -> next;
}
}
int main() {
linklist li;
li.additem(1315,"Mary");
li.additem(1307,"John");
li.additem(1293,"Kim");
li.additem(1270,"Marty");
li.additem(1258,"Linda");
li.display();
cout << endl << "Add Students - '0' to end" << endl;
string student;
int studentnum;
while (student != "0") {
cout << "Student Name: ";
cin >> student;
if (student != "0") {
cout << "Student Number: ";
cin >> studentnum;
cout << endl;
li.insertitem(studentnum,student);
}
}
cout << endl;
li.display();
cin.ignore();
cin.get();
return 0;
}
Re: Linked List - Inserting In Order
Hey friend try to understand these codes. it will guide u..
#include <iostream.h>
#include <stdlib.h>
// node structure
struct link
{
int iNo;
char *strName;
link *next;
};
// class for the operations
class MyClass
{
private:
protected:
public:
MyClass();
link *first;
void AddItem(int, char*);
void DisplayItem();
};
#include "list1.h"
MyClass::MyClass()
{
first = NULL;
}
void MyClass::AddItem(int iNum, char *strNam)
{
// cerate a new node
link *item = new link;
item->iNo = iNum;
item->strName = strNam;
// for the very first item in the list &&
// for item greater that the first node
if(first == NULL || iNum > first->iNo)
{
item->next = first;
first = item;
}
// for new node as intermediate node
else
{
link *target = NULL;
for(target = first; target->next != NULL; target = target->next)
{
if((target->iNo > iNum) && (target->next->iNo < iNum))
{
// this is the correct place for insertion of the node
item->next = target->next;
target->next = item;
break;
}
}
}
}
void MyClass::DisplayItem()
{
link *pDis = NULL;
for(pDis = first; pDis != NULL; pDis = pDis->next)
{
cout<<pDis->iNo<<"\n";
}
}
void main()
{
MyClass cls;
cls.AddItem(1,"India");
cls.AddItem(7, "Avaneesh");
cls.AddItem(5, "Good");
cls.AddItem(3, "Hello");
cls.AddItem(2, "Hi");
cls.DisplayItem();
}