一、头文件,每个结点包括数据和指针
#pragma once
#include<iostream>
struct Node
{
int data;
Node *next;
};
class Linlist
{
private:
Node * Head;
public:
Linlist();
void CreatList1(int n);
void CreatList2(int n);
int Insert(int i, int e);
int Delete(int i);
int GetData(int i);
int Search(int obj);
int ListLength();
void Display();
};
二、在cpp文件中重新定义基本操作函数
#include "stdafx.h"
#include"Linlist.h"
using namespace std;
Linlist::Linlist() //构造函数
{
Head = new Node;
Head->next = NULL;
}
void Linlist::CreatList1(int n) //头插入法创建链表
{
Node *p;
Node *temp;
p = Head;
cout << "请依次输入" << n << "个链表的值:";
for (int i = 1; i <= n; i++)
{
temp = new Node;
cin >> temp->data;
temp->next = p->next;
p->next = temp;
}
}
void Linlist::CreatList2(int n) //尾插入法创建链表
{
Node *p;
Node *temp;
p = Head;
cout << "请依次输入" << n << "个链表的值:";
for (int i = 0; i < n; i++)
{
temp = new Node;
cin >> temp->data;
p->next = temp;//p本来是最后一个结点,下一个结点为空,现在令它的下一结点为新输入的节点temp
p = temp;//然后再令temp变成新的最后一个结点
p->next = nullptr;//因此,temp的下一结点必须为空
}
}
int Linlist::Insert(int i, int e) //在i处插入e
{
Node *temp;
temp = Head;
int j = 0;
while (temp&&j < i - 1)//遍历链表,让temp一直向后移动,不断指向下一结点
{
temp = temp->next;
j++;
}
if (!temp)//如果到链表末尾,也就是text为空说明第i个元素不存在
{
cout << "第"<<i<<"个元素不存在,插入失败";
return -1;
}
else
{
Node *s;
s = new Node;
s->data = e;
s->next = temp->next;//插入s,原来temp的下一结点变成s的下一结点
temp->next = s;//然后s变成temp的下一结点
}
}
int Linlist::Delete(int i) //删除i处的数据
{
Node *temp;
temp = Head;
int j = 0;
while (temp&&j < i - 1)//遍历链表
{
temp = temp->next;
j++;
}
if (!temp)
{
cout << "第" << i << "个元素不存在,删除失败";
return -1;
}
else
{
Node *s;
s = temp->next;//temp的下一个结点就是第i个点,将它赋给s
temp->next = s->next;//让temp直接指向s的下一个结点,再把s删除
delete s;
}
}
int Linlist::GetData(int i) //查找第i个元素
{
Node *temp;
temp = Head;
int j = 0;
while (temp&&j < i - 1)
{
temp = temp->next;
j++;
}
if (!temp)
{
cout << "第" << i << "个元素不存在,查找失败";
return -1;
}
else
{
cout << i << "处的数据为:" << temp->next->data << endl;
return temp->next->data;
}
}
int Linlist::Search(int obj) //查找链表中有无与obj匹配的数据项
{
int j = 1;
Node *temp;
temp = Head->next;
while (temp&&temp->data != obj)
{
temp = temp->next;
j++;
}
if (temp == NULL)
{
cout << "该链表中无此元素" << endl;
return 0;
}
else
{
cout << "在该链表中的第" << j << "个元素等于" << obj << endl;
return j;
}
}
int Linlist::ListLength() //计算链表长度
{
Node *temp;
temp = Head;
int j = 0;
while (temp)
{
temp = temp->next;
j++;
}
cout << "该链表的长度为:" << j - 1 << endl;
return j;
}
void Linlist::Display() //遍历链表
{
Node *temp;
temp = Head->next;
int e;
cout << "该链表的遍历依次为:";
while (temp)
{
e = temp->data;
cout << e << endl;
temp = temp->next;
}
cout << endl;
}
三、测试主函数
int main()
{
int user_num;
cout << "请输入链表的长度:";
cin >> user_num;
Linlist list1;
Linlist list2;
list1.CreatList1(user_num);
cout << "头插入法创造的链表:" << endl;
list1.Display();
list1.Insert(2, 92);
list1.Display();
list1.GetData(2);
list1.Search(11);
list1.Search(92);
list1.Delete(3);
list1.Display();
list1.ListLength();
list2.CreatList2(4);
list2.Display();
}
四、程序运行结果