#include <stdio.h>
#include <stdlib.h>
/*节点结构制定*/
typedef struct _st_node
{int data;
struct _st_node *next;
}st_node;
/*操作函数声明*/
int length(st_node *head);
void travel_list(st_node *head);
st_node *findkth(int k,st_node *head);
st_node *findvalue(int n,st_node *head);
st_node *insert(int x,int i,st_node *ptrl);
/*主函数:建表,调用操作函数*/
int main(int argc,char**argv)
{
st_node *head =NULL;
st_node *new_node;
int i;
for(i=0;i<10;i++)
{ new_node=malloc(sizeof(st_node));
if (NULL==new_node) {
printf("malloc failure\n");
return 0;
}
new_node->data=i+1;
if(head==NULL){
head=new_node;
}else{
new_node->next = head;
head = new_node;
}
}
/*操作函数调用*/
travel_list(head);
length(head);
findkth(8,head);
findvalue(7,head);
insert(48,5,head);
return 0;
}
/* 函数名:travel()
* 作用:头插法遍历,打印每一个data值*/
void travel_list(st_node *head)
{
st_node *node=head;
printf("头插法遍历\n");
while(node != NULL)
{
printf("data:%d\n",node->data);
node=node->next;
}
return;
}
/*函数名:length()
* 作用:打印表长*/
int length(st_node *head)
{
st_node* node=head;
int j=0;
while(node != NULL )
{
node=node->next;
j++;
}
printf("\n打印表长:\nlength=%d\n",j);
return ;
}
/*函数名:findkth()
* 作用:找到表中第k个元素的值并打印*/
st_node *findkth(int k,st_node *head)
{
st_node *node=head;
int i=0;
while(node!=NULL&&i<k)
{ node=node->next;
i++;
}
if (i==k)
{ printf("\n按序号查找:\nthe kth of NO.%d=%d\n",k,node->data);
}
else return NULL;
}
/*函数名:findevalue()
* 作用:按值查找,是否有该值,有就输出*/
st_node *findvalue(int n,st_node *head)
{
st_node *node = head;
int i=1;
while(node!=NULL&&(node->data)!=n)
{ node=node->next;
i++;
}
printf("data[%d]:findvalue=%d\n",i,node->data);
return head ;
}
/*函数名:insert()
* 作用:在第i个结点后插入一个值为x的新结点*/
st_node *insert(int x,int i,st_node *ptrl)
{
st_node *p,*new_one; //创建新结点
if (i==0){ //新结点在表头
new_one=(st_node*)malloc(sizeof(st_node)); //分配空间
new_one->data=x;
new_one->next=ptrl;
return new_one;
}
p=findkth(i,ptrl);
if (p==NULL){
printf("error");
return NULL;
}
else{
new_one=(st_node*)malloc(sizeof(st_node));
new_one->data=x;
new_one->next = p->next;
p->next=new_one;
return ptrl;
}
}