C++实现链表基本操作

main.cpp

#include <iostream>
#include <string>
using namespace std;

struct Info
{
string name;    //姓名
int id;     //学号
Info(string n,int d):name(n), id(d){}
};

struct Node
{
Info val;
Node *next;
Node(Info x) :val(x), next(NULL){}
};

{
public:
//构造函数

void InsertHead(Info val);  //在链表头部插入结点
void Insert(Info val, int pos); //在链表pos位置插入结点
void InsertLast(Info val);  //在表尾插入结点

//删除结点
void Remove(Info val);
//得到链表长度
int Length();
//链表反序
void Reverse();
//查找结点位置
int Find(Info val);
//打印链表
void traverList();
//析构函数
private:
int length;
};



using namespace std;

//构造函数
{
length = 0;
}

//析构函数
{
Node *temp;
for (int i = 0; i < length; i++)
{
delete temp;
}
}

//得到链表长度
{
return length;
}

//在链表头部插入结点
{
Insert(val, 0);
}
{
Insert(val, length);
}

//在pos位置插入结点
void LinkList::Insert(Info val, int pos)
{
if (length + 1 < pos || pos < 0)
{
cout << "pos must be greater than zero or less than ListSize" << endl;
return;
}

Node *temp = head;
Node *node = new Node(val);//创建一个node
if (pos == 0)
{
node->next = temp;
}
else
{   //插入时非表头时
for (int index = 1; temp != NULL && index < pos;index++)
{
temp = temp->next;
}
node->next = temp->next;
temp->next = node;
}
length++;
return;
}

//删除结点
{
int pos = Find(val);
if (pos == -1)
{
cout << "Delete failed" << endl;
return;
}
if (pos == 1)
{
length--;
return;
}
int index = 2;
Node *temp = head;
while (index < pos)
temp = temp->next;
temp->next = temp->next->next;
length--;
}

//查找结点位置
{
Node *temp = head;
int index = 1;
while (temp != NULL)
{
if (temp->val.name == val.name && temp->val.id == val.id)
return index;
temp = temp->next;
index++;
}
return -1; //不存在返回-1
}

//链表反序
{
if (head == NULL)
return;
Node *curNode = head, *nextNode = head->next, *temp;
while (nextNode != NULL)
{
temp = nextNode->next;
nextNode->next = curNode;
curNode = nextNode;
nextNode = temp;
}
}

//打印链表
{
if (head == NULL)
{
cout << "LinkList is empty" << endl;
return;
}
Node *temp = head;
while (temp != NULL)
{
cout << temp->val.name << "," << temp->val.id << endl;
temp = temp->next;
}
cout << endl;
}

main.cpp

// main.cpp : 测试链表功能。
#include <iostream>
#include <string>
using namespace std;

int main()
{
Info val1("Kevin", 1), val2("Cathy", 2), val3("Lucy", 3), val4("Gravin",4);

//测试插入功能
cout << "Insert test:" << endl;

//测试反序功能
cout << "reverse test:" << endl;
cout << "reversed linklist is:" << endl;

//测试删除功能
cout << "remove test:" << endl;
cout << "the length of linklist is:" << endl;
cout << head.Length() << endl;
}