#include <iostream>
using namespace std;
struct MyList{
int val;
MyList *next;
};
//在第i个位置插入e
void ListInsert(MyList *L, int i, int *e) {
int j = 1; //计数器
MyList *p;
p = L; //头指针给p;
while (p && j < i) {
p = p->next;
j++;
}
if (!p || j > i) {
throw "ERROR!";
}
MyList *s = new MyList;
s->val = *e;
s->next = p->next;
p->next = s;
}
//delete第i个元素,并用e返回其值
void ListDelete(MyList *L, int i, int *e) {
int j = 1;
MyList *p = L;
while (p && j < i) {
p = p->next;
j++;
}
if (!(p->next) || j > i) {
throw"ERROR";
}
MyList *q = p->next;
p->next = q->next;
*e = q->val;
free(q);
}
//查找第i个元素并用e返回值
void GetElem(MyList *L, int i, int *e) {
int j = 1; //计数器
MyList *p;
p = L->next;
while (p && j < i) {
p = p->next;
j++;
}
if (!p || j > i) {
throw "ERROR!";
}
*e = p->val;
}
int main() {
MyList *head; //头指针
MyList *r; //循环指针
head = new MyList;
head->next = NULL;
r = head;
//循环创建链表
for (int i = 0; i < 10; i++) {
MyList *p = new MyList;
p->val = i;
r->next = p;
r = p;
}
r->next = NULL;
int *e = new int(-1); //指针初始化
/*GetElem(head, 11, e);
cout << *e << endl;*/
//ListInsert(head, 4, e);
//ListDelete(head, 10, e);
//输出链表
r = head->next;
while (r) {
cout << r->val << endl;
r = r->next;
}
return 0;
}
结构体实现单链表
最新推荐文章于 2022-11-08 21:47:27 发布