链表
#include <iostream>
using namespace std;
//定义链表结点
struct ListNode {
int val;
ListNode* next;
};
//定义链表
typedef ListNode* LinkedList;
//插入元素
void insert(LinkedList& L, int pos, int value) {
ListNode* newNode = new ListNode;
newNode->val = value;
ListNode* p = L;
for (int i = 1; i < pos; i++) {
if (p->next) {
p = p->next;
}
else {
cout << "插入位置错误" << endl;
delete newNode;
return;
}
}
newNode->next = p->next;
p->next = newNode;
}
//删除元素
void remove(LinkedList& L, int pos) {
ListNode* p = L;
for (int i = 1; i < pos; i++) {
if (p->next) {
p = p->next;
}
else {
cout << "删除位置错误" << endl;
return;
}
}
ListNode* q = p->next;
p->next = q->next;
delete q;
}
//查找元素位置
int find(LinkedList& L, int value) {
ListNode* p = L->next;
int pos = 1;
while (p) {
if (p->val == value) {
return pos;
}
pos++;
p = p->next;
}
return -1;
}
//查找指定位置元素
int get(LinkedList& L, int pos) {
ListNode* p = L->next;
for (int i = 1; i < pos; i++) {
if (p) {
p = p->next;
}
else {
cout << "位置错误" << endl;
return -1;
}
}
return p->val;
}
//遍历链表
void traverse(LinkedList& L) {
ListNode* p = L->next;
while (p) {
cout << p->val << " ";
p = p->next;
}
cout << endl;
}
评论区