C++实现静态链表
注意理解headp,searchp,followp,newnodep的角色与功能.
特别是searchp,followp.
// 静态链表.cpp: 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include<iostream>
using namespace std;
class node
{
public:
int data;
node *next;
};
class link
{
private:
node * headp;
protected:
int count;
public:
link();
~link();
void create(int *data, int size); //初始化链表
void clearlink(); //清空链表
void display(); //打印链表元素
int getlen(); //获取链表实际长度
void insert(int position, int item); //指定位置插入元素
void remove(int position); //指定位置删除元素
void update(int position, int item); //指定位置更新元素
int getonedata(int position); //指定位置获取元素
};
link::link()
{
count = 0;
headp = new node;
headp->next = NULL;
}
link::~link()
{
clearlink();
delete headp;
count = 0;
}
void link::create(int * data, int size)
{
node *searchp = headp, *newnodep;
for (int i = 0; i < size; i++)
{
newnodep = new node;
newnodep->data = data[i];
newnodep->next = NULL;
searchp->next = newnodep;
searchp = newnodep;
count++;
}
searchp->next = NULL; //通过searchp实现循环的上下连接
}
void link::clearlink()
{
node *searchp = headp, *followp = headp;
while (searchp!=NULL)
{
followp = searchp;
searchp = searchp->next;
delete followp; //删除关键语句
}
headp->next = NULL;
count = 0;
}
void link::display()
{
node *searchp = headp->next;
while (searchp != NULL)
{
cout << searchp->data << " ";
searchp = searchp->next;
}
cout << endl;
}
int link::getlen()
{
return count;
}
void link::insert(int position, int item)
{
node *searchp = headp->next, *followp = headp, *newnodep;
for (int i = 1; i < position&&searchp != NULL; i++)
{
followp = searchp;
searchp = searchp->next;
}
newnodep = new node;
newnodep->data = item; //注意语句顺序
newnodep->next = searchp;
followp->next = newnodep;
count++; //理解searchp,followp的思想
}
void link::remove(int position)
{
node *searchp = headp->next, *followp = headp;
for (int i = 1; i < position&&searchp != NULL; i++)
{
followp = searchp;
searchp = searchp->next;
}
followp->next = searchp->next;
count--; //理解searchp,followp的思想
delete searchp;
}
void link::update(int position, int item)
{
node *searchp = headp->next;
for (int i = 1; i < position&&searchp != NULL; i++)
{
searchp = searchp->next;
}
searchp->data = item; //理解searchp的思想
}
int link::getonedata(int position)
{
node *searchp = headp->next;
for (int i = 1; i < position&&searchp != NULL; i++)
searchp = searchp->next;
return searchp->data; //理解searchp的思想
}
int main()
{
int data[8] = { 1,2,3,4,5,6,7,8 };
int size = sizeof(data) / sizeof(data[0]);
link l = link();
l.create(data, 8);
l.display();
l.insert(2, 10);
l.display();
l.remove(2);
l.display();
l.update(2, 15);
l.display();
cout << "当前长度为:" << l.getlen() << endl;
cout << "第二个元素为:" << l.getonedata(2) << endl;
l.clearlink();
cout << "当前长度为:" << l.getlen() << endl;
system("pause");
return 0;
}