1. 分别头插入法或尾插入法建立带头节点的单链表。
2. 实现单链表上的插入,删除,查找,修改,计数,输出等基本操作。
提示
struct link
{ int data ;
struct link *next ;
}
//尾插入法建立带头结点的单链表
link *create()
{
struct link *p = (struct link*)malloc(sizeof(struct link));
p->data = 0;
p->next = 0;
return p;
}
//输出单链表
void print ( link *head)
{
struct link *p = head;
if(!p)return;
while(p->next)
{
printf("%d \n",p->next->data);
p=p->next;
}
}
//在单链表查找第x个结点
link *locate ( link *head , int x )
{
struct link *p = head;
if(!p)return (struct link *)0;
while(p->next)
{
if(x == p->next->data)return p->next
p=p->next;
}
return (struct link *)0;
}
//在head为头指针的单链表中,删除值为x的结点
void delete ( link *head , int x)
{
struct link *p = head,*j;
if(!p)return (struct link *)0;
while(p->next)
{
if(x == p->next->data)
{
j=p->next;
p->next=p->next->next;
free(j);
}
p=p->next;
}
return;
}
//在head为头指针的单链表中,在第x个结点之后插入值为y的结点。
void insert (link *head , int x , int y )
{
struct link *p = head,*j;
if(!p)return (struct link *)0;
while(--x)
{
if(!(p->next))
p=p->next;
else
return;
}
j=p->next;
p->next= (struct link*)malloc(sizeof(struct link));
p->next->data=y;
p->next->next=j;
return;
}
//将单链表p中所有为x的元素改成值为y
void change ( link *p , int x , int y )
{
struct link *j;
if(!p)return;
while(p->next)
{
if(p->next->data == x)p->next->data=y;
p=p->next;
}
return;
}
//统计单链表中结点个数
int count ( link *h )
{
int i=0;
if(!h)return;
while(h->next)
{
i++;
h=h->next;
}
return i;
}