链表的插入(任何位置):
int Link1Insert(Node **l, int p, int e)
{
int i = 1, count = 1;
if((NULL == *l) && (p == 1))
{
(*l) = (Node *)malloc(sizeof(Node));
(*l)->next = NULL;
(*l)->data = e;
return success;
}
else if(((NULL == *l) && (p > 1)) || (p < 1))
{
return failure;
}
else
{
Node *n = (Node *)malloc(sizeof(Node));
Node *q = *l;
while(q->next)
{
count++;
q = q->next;
}
if(p > count + 1)
return failure;
else if(p == count + 1)
{
q->next = n;
n->next = NULL;
n->data = e;
return success;
}
else if(p < count + 1 && p > 1)
{
q = *l;
while(i < p - 1)
{
q = q->next;
i++;
}
n->next = q->next;
q->next = n;
n->data = e;
return success;
}
else
{
n->next = *l;
*l = n;
n->data = e;
return success;
}
}
}
我用的是if条件判断语句去把是不是插入第一个位置,不含有头结点的链表和有头结点的链表的区别就在于是否是插入第一个位置,如果插入的是第一个位置就改变头指针的指向。所以要传入地址。上面我写的这种方法可能不是最简洁的方法。
链表倒序:
int LinkReverse(Node *l)
{
if(NULL == l)
{
return FAILURE;
}
Node *p = l->next;
l->next = NULL;
while(p != NULL)
{
Node *q = p;
p = p->next;
q->next = l->next;
l->next = q;
}
return FAILURE;
}