数据结构专栏:数据结构_脑子不好的小菜鸟的博客-CSDN博客
/*链表的相关操作*/
#define ok 1
#define error 0
#define overflow -2
typedef int status;
typedef int elemtype;
typedef struct node
{
elemtype data;
struct node* next;
}Lnode, *Llist;
/*status*/void create01(Llist& L, int n)
{
int i;
L = (Llist)malloc(sizeof(Lnode));/**/
//if (L == NULL)
// return error;
L->next = NULL;
Llist p, s;//p:追踪链尾,s:新建节点
p = L;/**/
printf("请输入你要创建的%d个元素的值(尾插,顺序创建)\n", n);
for (i = 0; i < n; i++)
{
s = (Llist)malloc(sizeof(Lnode));
//if (s == NULL)
// return error;
scanf("%d", &s->data);
p->next = s;
//尾插
p = p->next;
}
p->next = NULL;/**/
//return ok;
}
void create02(Llist& L)
{
L = (Llist)malloc(sizeof(Lnode));/*创建头节点*/
L->next = NULL;
//尾部插入节点
printf("请输入你要创建的元素值,以0结尾(尾插,顺序创建)\n");
int val;
scanf("%d", &val);
Llist s, p;
p = L;
while (val)
{
s = (Llist)malloc(sizeof(Lnode));
s->data = val;
//尾插
p->next = s;
p = p->next;
scanf("%d", &val);
}
p->next = NULL;/**/
}
void create03(Llist& L)
{
L = (Llist)malloc(sizeof(Lnode));/**/
L->next = NULL;
printf("请输入你要创建的元素值,以0结尾(头插,逆序创建)\n");
int val;
scanf("%d", &val);
Llist s;
while (val)
{
s = (Llist)malloc(sizeof(Lnode));
s->data = val;
//头插
s->next = L->next;
L->next = s;
scanf("%d", &val);
}
}
void print(Llist& L)
{
Llist q;/*注意不是Lnode,因为要指向next指针*/
q = L->next;
printf("打印链表元素\n");
while (q)
{
printf("%d ", q->data);
q = q->next;
}
printf("\n");
}
int getnum(Llist L)
{
Llist q;/*注意不是Lnode,因为要指向next指针*/
int n = 0;
q = L->next;
while (q)
{
q = q->next;
n++;
}
return n;
}
status myinsert(Llist& L, int i, int e)
{
if (i < 1)
return error;
Llist q = L;
int j = 0;
while (q != NULL && j < i - 1)
{
j++;
q = q->next;
}
if (q == NULL)
return error;
Llist s = (Llist/*注意:不要打星号*/)malloc(sizeof(Lnode));
s->data = e;
s->next = q->next;
q->next = s;
return ok;
}
status myerase(Llist& L, int i)
{
if (i < 1)
return error;
int j = 0, e;
Llist q = L;
while (q != NULL && j < i - 1)
{
j++;
q = q->next;
}
if (q == NULL)
return error;
e = q->next->data;
Llist p = q->next;
q->next = q->next->next;
free(p);
p = NULL;
return e;
}
Llist locat(Llist& L, int i)
{
if (i < 1)
return NULL;
int j = 0;
Llist q = L;
while (q != NULL && j < i/**/)
{
j++;
q = q->next;
}
if (q == NULL)
return NULL;
return q;
}
int main()
{
Llist L1;
int n;
//尾插---->正向输出----->都需要一个指针p去跟踪链表末尾
//已知元素个数创建
//printf("请输入你要创建的链表元素个数:\n");
//scanf("%d", &n);
//create01(L1, n);
create02(L1);
print(L1);
printf("链表元素个数为:%d\n", getnum(L1));
//Llist L2;
头插---->逆序输出
以0为结尾输入的创建
//create03(L2);
//print(L2);
//printf("链表元素个数为:%d\n",getnum(L2));
int i, e;
//注意插入和删除数据都是要定位到该位置的前面一个
//插入数据
printf("请输入你要插入的位置和数据\n");
scanf("%d%d", &i, &e);
myinsert(L1, i, e);
print(L1);
//删除数据
printf("请输入你要删除的位置\n");
scanf("%d", &i);
e = myerase(L1, i);
if (e == 0)
printf("删除位置非法,删除失败\n");
else
{
printf("删除的数据为:%d,删除成功\n", e);
print(L1);
}
//定位
printf("请输入你要定位的元素位置\n");
scanf("%d", &i);
Llist q = locat(L1, i);
if (q == NULL)
printf("定位非法,定位失败\n");
else
printf("%p\n", q);
return 0;
}