## 数据结构——单链表的数据插入删除查询##
二话不说,上代码
/** * 命名空间: std * 功 能: 单链表的基本算法和链表的建立 * 类 名: * * Ver 变更日期2017.5.8 负责人 wall * ─────────────────────────────────── * V0.01 2017.5.8 Wall 初版 * * Copyright (c) 2017 Lir Corporation. All rights reserved. * *备注:本程序所有数据类型DataType均为int型 */
#include <iostream>
using namespace std;
struct Node
{
int data;
Node*next;
};
class Linklist
{
public:
Linklist()
{
first = new Node;
first->next = NULL;
}
Linklist(int a[], int n)//尾插法
{
first = new Node;
first->next = NULL;
for (int i = 0; i<n; i++)
{
Node*p; p = new Node; p->data = a[i];
p->next = first->next;
first->next = p;
}
}
void Printlist();
int Get(int i); int Locate(int x); int length();
void Insert(int i, int x);
int Delete(int i);
private:
Node*first;
};
int Linklist::Locate(int x)//值查
{
Node*p; p = new Node;
p = first->next;
int count = 1;
while (p != NULL)
{
if (p->data == x)return count;
p = p->next;
count++;
}
return 0;
}
void Linklist::Insert(int i, int x)//插入
{
Node*p; p = new Node; p = first;
int count = 0;
while (p != NULL&&count<i - 1)
{
p = p->next;
count++;
}
if (p == NULL)throw"输入错误";
else
{
Node*q; q = new Node; q->data = x;
q->next = p->next;
p->next = q;
}
}
int Linklist::Delete(int i)//删除
{
Node*p; p = new Node; int x;
p = first; int count = 0;
while (p != NULL&&count<i)
{
p = p->next;
count++;
}
if (p == NULL || p->next == NULL) throw"输入错误";
else
{
Node*q; q = new Node;
q = p->next; x = q->data;
p->next = q->next;
delete q;
return x;
}
}
void Linklist::Printlist()//遍历
{
cout << "链表为";
Node*p; p = new Node;
p = first->next;
while (p != NULL)
{
cout << p->data << ',';
p = p->next;
}
cout << endl;
}
int Linklist::length()//长度
{
Node*p; p = new Node; int count = 0;
p = first->next;
while (p != NULL)
{
p = p->next;
count++;
}
return count;
}
int main()
{
int n = 0;
int i, x,h;
int a[100];
cout << "Please enter the length of the array:"; cin >>h;
for (int i = 0; i<h; i++)
{
cin >> x; a[i] = x;
}
Linklist c(a, h);
c.Printlist();
while (1)
{
int m;
cout << "-------------操作选项-----------" << endl;
cout << "1:在指定位置插入" << endl;
cout << "2:在指定位置删除" << endl;
cout << "3:在指定位置查找" << endl;
cout << "0:结束程序" << endl;
cout << "---------------------------------" << endl;
cin >> m;
if (m == 1)
{
cin >> i >> x;
if (i<0 || i>c.length())
cout << "输入错误" << endl;
else {
c.Insert(i + 1, x);
c.Printlist();
}
continue;
}
else if (m == 2)
{
cin >> i;
if (i<0 || i>c.length())
cout << "输入错误" << endl;
else {
cout << c.Delete(i - 1) << endl;
c.Printlist();
}
continue;
}
else if (m == 3)
{
cin >> x;
if (c.Locate(x)>0)
cout << c.Locate(x) - 1 << endl;
else cout << "输入错误" << endl;
continue;
}
else if (m == 0)
{
return 0;
}
}
}
希望我的分享能对大家有用。