1.编程实现一个单链表的打印
void print(node *head)
{
node *p;
int index=0;
//链表为空
if(p->next==NULL)
{
printf("Link is empty\n");
return;
}
//遍历链表
p=head->next;
while(p!=NULL)
{
printf("The %dth node is:%d\n",++index,p->data);
}
p=p->next;
}
}
2.编程实现一个单链表结点的查找
//查找单链表pos位置的节点,返回节点指针
//pos从0开始,返回head节点
node *search_node(node *head,int pos)
{
node *p=head->next;
//pos位置不正确
if(pos<0)
{
printf("incorrect position to search node!\n");
return NULL;
}
if(pos==0)//在head位置,返回head
{
return head;
}
if(p==NULL)
{
printf("Link is empty!\n");//链表为空
return NULL;
}
while(--pos)
{
if((p=p->next)==NULL)
{//超出链表范围
printf("incorrect position to search node!");
break;
}
}
return p;
}