# 链表

/**
*单链表的建立，查找，插入，删除，逆序
**/
#include <stdio.h>
#include <malloc.h>

int num;
struct node *next;//指针域
} Node;

//创建一个单链表
Node *creat() { //定义函数creat1()

int n;
scanf("%d", &n);

while (n>0) {
p = (Node *)malloc(sizeof(Node));//分配第一个结点空间
p->num =n;
scanf("%d", &n);
}

}

//打印节点
Node *p;
printf("\n");
while (p != NULL) { //输出链表
printf("%d\n", p->num);
p=p->next;
}
}

//计算单链表的长度

{
Node *p;//定义p为工作指针
int n=0;

while (p != NULL)
{
n++;
p=p->next;//指针后移
}
return n;
}

/*在单链表中按照指定的值实现元素的查找
*查找过程挨个元素比较判断是否相等的过程
*/
{
while(p && p->num != n)//链表不为空，同时没有到达指定的结点
p = p->next;//指针后移

if(p->num == n)//已找到
return p;
else
return NULL;

}

/*单链表的插入
*/
Node *insert(Node *head, int pos, int num)
{
int i = 1;
Node *pre; //pre为前驱结点
Node *p;//插入的结点为p

while (pre->next && i< pos )
{
pre = pre->next;//查找第n个位置的前驱结点
i++;
}

p = (Node *)malloc(sizeof(Node));
p->num = num;
p->next = pre->next;
pre->next = p;

}

/*单链表的删除
*在链表中删除值为num的元素

*/
{
Node *p, *pre;//pre为前驱结点，p为查找的结点

while(p->num != num) //查找值为num的元素
{
pre = p;
p = p->next;
}

if (p->num == num)
{
pre->next = p->next;//删除操作，将其前驱next指向其后继
free(p);//删除以后回收结点
}
else
printf(" not fount the delete num in the link\n");

}

void main() {
int count;
int num;
int pos;

printf("iput find element:");
scanf("%d", &num);

if(p)
printf("the element find %d\n", p->num);
else
printf("don't find\n");
scanf("%d", &pos);
scanf("%d", &num);

printf("*********after insert*******\n");

scanf("%d", &num);
printf("*********after delete num*******\n");
}

-----------------------------------------------------------------------------

带有头结点的单链表逆序

/**
*单链表数据结点逆序
*/
{
Node *p, *q;

while(p)
{
q = p;//q保存当前p的工作指针
p=p->next;//指针p后移

}