问题描述:
创建一个链表类,该链表对象具有插入节点至特定位置(或头结点)、查询节点对象、删除节点对象、返回节点长度等功能。节点的功能为:包含学生信息(姓名,ID)和节点指针(指向下一节点)。
功能实现:
list.h
#pragma once
#ifndef LIST_H_
#define LIST_H_
//创建string 类头文件
#include<string>
using namespace std;
struct Info
{
string name;
int id;
};
struct Node
{
Info val;
Node *next;
Node(Info x) :val(x), next(NULL) {}
};
class List
{
private:
Node * head;
int length;
public:
List();
~List();
int len();
int find(const Info val);
void insert(Info val, int n = 0);
void remove(Info val);
void print();
};
#endif
list.cpp
#include<iostream>
#include"list.h"
using namespace std;
List::List()
{
head = NULL;
length = 0;
}
List::~List()
{
Node *temp;
for (int i = 0; i < length; i++)
{
temp = head;
head = head->next;
delete temp;
}
}
int List::len()
{
return length;
}
int List::find(const Info val)
{
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;
}
void List::insert(Info val, int n)
{
if (n < 0)
{
cout << "the n must be greater than or equal to zero. " << endl;
return;
}
int index = 1;
Node *temp = head;
Node *node = new Node(val);
if (n == 0)
{
node->next = head;
head = node;
length++;
return;
}
while (temp != NULL && index < n)
{
temp = temp->next;
index++;
}
if (temp == NULL)
{
cout << "insert fail !" << endl;
return; //避免空指针异常
}
node->next = temp->next;
temp->next = node;
length++;
}
void List::remove(Info val)
{
int n = find(val);
if (n == -1)
{
cout << "remove fail ! " << endl;
return; //避免空指针异常
}
if (n == 1)
{
head = head->next;
length--;
return;
}
int index = 2;
Node *temp = head;
while (index < n)
{
temp = temp->next;
}
temp->next = temp->next->next;
length--;
}
void List::print()
{
if (head == NULL)
{
cout << "list is already empty ! " << endl;
return; //避免空指针异常
}
Node *temp = head;
while (temp != NULL)
{
cout << temp->val.name << " , " << temp->val.id << endl;
temp = temp->next;
}
cout << endl;
}
功能验证:
main.cpp
#include<iostream>
#include"list.h"
using namespace std;
int main()
{
List list;
Info items[5] = { { "Alpha", 1 },{ "Beta",2 },{ "Cigma", 3 },{ "Delta", 4 },{ "Epsilon",5 } };
cout << "insert test: " << endl;
for (int i = 0; i < 5; i++)
{
list.insert(items[i]);
}
cout << "The list length is : " << list.len() << endl;
list.print();
cout << "--------------*---------------" << endl;
list.insert(items[2]);
list.insert(items[1], 4);
list.insert(items[1],1);
cout << "the list length is : " << list.len() << endl;
list.print();
cout << "remove test: " << endl;
list.remove(items[2]);
cout << "The list length is : " << list.len() << endl;
cout << "-----------------***------------" << endl;
list.print();
list.remove(items[4]);
cout << "The list length is : " << list.len() << endl;
list.print();
cout << "-----------------****------------" << endl;
return 0;
}
【注:linux环境编译,可能的异常:(dump core),主要原因为空指针异常,因此需要添加return;】
参考文章:c++实现链表基本操作