楼主编程小白一个 最近在学数据结构,分享下自己的链表学习代码,欢迎大家指教和讨论。
如有不懂,也欢迎提问,不过我真是菜鸡一个哈哈。
#include<iostream>
#include<malloc.h>
using namespace std;
typedef int ElementType;
typedef struct LNode *List; //结构体指针
struct LNode
{
ElementType data;
List next;
};
List L;
List MakeEmpty(); //初始化链表
int Length(List L); //遍历链表求链表的长度
List Findk(int k, List L); //按序号查找
int FindX(ElementType X, List L); //按值查找
List Insert(ElementType X, int i, List L); //讲X插入到i-1个结点之后
bool Delete(int i, List L); //删除第i个结点
void print(List L); //输出链表元素
List MakeEmpty() {
List L = new LNode;
L = NULL;
return L;
}
//求表长
int Length(List L) {
List p = L; //指向链表头结点;
int len = 0;
while (p) {
p = p->next;
len++;
}
return len;
}
//按序查找
List Findk(int k, List L) {
List p = L;
int i = 1;
while (p && i < k) {
p = p->next;
i++;
}
if (i == k) //注意K可能是负数也是输入错误
return p;
else
return NULL;
}
//按值查找
int FindX(ElementType X, List L) {
List p = L;
int count = 1;
while (p && p->data != X){
p = p->next;
count++;
}
return count;
}
//插入
List Insert(ElementType X, int i, List L) {
List tmp, p;
tmp = new LNode;
tmp->data = X;
if (i == 1) {
tmp->next = L;
return tmp; //返回新表头
}
else {
//查找位序为i-1的结点看是否在内
p = Findk(i - 1, L);
if (p == NULL) {
cout << "插入未知参数错误" << endl;
delete tmp;
return NULL;
}
else {
tmp->next = p->next;
p->next = tmp;
return L; //返回表头
}
}
}
//删除第i个结点
bool Delete(int i, List L) {
List tmp, p;
if (i == 1){
tmp= L;
if (L != NULL)L = L->next;
else return NULL;
delete tmp;
return true;
}
p = Findk(i - 1, L);
if (p == NULL) {
cout << "第" << i - 1 << "个结点不存在,删除失败" << endl;
return false;
}
else if (p->next == NULL) {
cout << "第" << i << "个结点不存在,删除失败" << endl;
return false;
}
else {
tmp = p->next;
p->next = tmp->next;
delete tmp;
return true;
}
}
//输出链表元素
void print(List L) {
int count = 0;
while (L) {
cout << L->data << "->";
L = L->next;
count++;
}
cout << endl;
if (count == 0) {
cout << "无数据输出" << endl;
}
}
int main()
{
List tmp;
L = MakeEmpty();
L = Insert(1, 1, L);
L = Insert(2, 2, L);
L = Insert(3, 3, L);
L = Insert(4, 4, L);
L = Insert(5, 5, L);
print(L);
int length = Length(L);
cout << "该链表的长度为" << length << endl;
int i; cout << "请输入你想搜寻的位置下标: ";
cin >> i;
tmp = Findk(i, L);
cout << "第"<<i<<"个下标对应的值为" << tmp->data << endl;
int x; cout << "请输入你想搜寻的元素的值: ";
cin >> x;
int q = FindX(x,L);
cout << "元素" << x << "在链表的位置是: " << q << endl;
int j; cout << "请输入你想删除的元素位置: ";
cin >> j;
if (Delete(j, L)){
cout << "删除后的链表为: ";
print(L);
}
}