闲来无事,学习一下链表,方便后面研究webkit的memorycache的LRU算法
#include <iostream>
#include "assert.h"
using namespace std;
class Student{
public:
Student *operator new();
void operator delete(void *);
public:
int m_studentID;
int m_score;
Student *next;
};
class Student;
class ListUtility{
public:
Student *createList();
void insertNode(Student **head,int num,Student *node);//在指定号码后插入新节点
void deleteNode(Student **head,int num);//删除指定号码的节点
void printList(Student *list);//输出链表
void collectRes(Student *list);
};
void ListUtility::printList(Student *list)
{
cout<<"print list start!"<<endl;
while(list){
cout<<list->m_studentID<<" "<<list->m_score<<endl;
list=list->next;
}
cout<<"print list end!"<<endl;
}
Student *ListUtility::createList()
{
int number;
int score;
Student *head;
Student *p1;
Student *p2;
int count=0;
while(cin>>number&&number){
p1=new Student;
if(!p1)
return NULL;
cin>>score;
if(++count==1)
head =p1;
else
p2->next=p1;
p2=p1;
p1->m_score=score;
p1->m_studentID=number;
}
p2->next=NULL;
p1=NULL;
return head;
}
void ListUtility::deleteNode(Student **head,int num)
{
Student *p1=*head;
Student *p2;
while(p1){
if(p1->m_studentID==num){
if(p1==*head){
*head=p1->next;
break;
}
else{
assert(p2);
p2->next=p1->next;
delete p1;
p1=NULL;
break;
}
}
p2=p1;
p1=p1->next;
}
}
void ListUtility::insertNode(Student **head,int num,Student *node)
{
Student *p1=*head;
if(num==0){//0默认插入到最前面
node->next=p1;
*head=node;
return;
}
while(p1){
if(p1->m_studentID==num){
node->next=p1->next;
p1->next=node;
}
p1=p1->next;
}
}
void ListUtility::collectRes(Student *list)
{
Student *p1;
p1=list;
Student *p2;
while(p1){
p2= p1->next;
p1->next=NULL;
delete p1;
p1 =p2;
}
}
int main(void)
{
ListUtility factory;
Student *myList=factory.createList();
factory.printList(myList);
Student newComming;
newComming.m_score=99;
newComming.m_studentID=24;
// factory.insertNode(&myList,3,&newComming);
factory.printList(myList);
factory.deleteNode(&myList,2);
factory.printList(myList);
factory.collectRes(myList);//上面的insert的是一个对象而链表中的是动态new的,不能直接delete
}
<pre name="code" class="cpp">