链表——单向链表

闲来无事,学习一下链表,方便后面研究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">


                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值