单链表由好多个结点构成 其中头节点可有可无 可以用来存放链表长度。
头指针必须有 每一个指针指向 下一个结点的数据域 头指针指向头结点 头结点中还有一个指针变量
指针域是一个结点类型的指针
#include<iostream>
using namespace std;
typedef int ElementType;
typedef int status;
typedef struct node {
ElementType data;
node* next;//node->next->date ai+1;
}node;
typedef node* linklist;
//单链表的读取
status getelem(linklist l, int i, ElementType* e)
{
int j;
linklist p;
p = l->next;
j = 1;
while (p && j < i)
{
p = p->next;
++j;
}
if (!p || j > i)
{
return -1;
}
*e = p->data;
return 0;
}
//单链表的插入
status listinsert(linklist l, int i,ElementType e)
{
int j;
linklist p, s;
p = l->next;
j = 1;
while (p&&j < i)
{
p = p->next;
j++;
}
if (!p || j >= i)
{
return -1;
}
s = (linklist)malloc(sizeof(node));
s->data = e;
s->next = p->next;
p->next = s;
//颠倒会覆盖 造成死循环
}
status listdelete(linklist l, int i, ElementType *e)
{
int j;
linklist p, q;
p = l->next;
j = 1;
while (p->next&&j < i)
{
p = p->next;
j++;
}
if (!p->next || j >= i)
{
return -1;
}
//p->next = p->next->next;
q = p->next;
p->next = q->next;
*e = q->data;
free(q);
}