单链表:
定义:
typedef int elemtp;
typedef struct node
{elemtp data;
struct node *next;}
linklist;
linklist *head,*p;
建立单链表:带头结点
linklist *creatlist()
{char ch;
int x;
linklist *head,*r,*p;
p=malloc(sizeof(linklist));
head=p;
p->next=Null;
r=p;
ch=getchar();
while(ch!=';?';)
{scanf("%d",&x);
p=malloc(sizeof(linklist));
p->data=x;
p->next=Null;
r->next=p;
r=r->next;
ch=getchar();
}
return(head);
}
建立单链表:不带头结点
linklist *creatlist()
{char ch;
int x;
linklist *head,*p,*r;
head=Null;
r=Null;
ch=getchar();
while(ch!=';?';)
{p=malloc(sizeof(linklist));
scanf("%d",&x);
p->data=x;
if(head==Null) head=p;
else
r->next=p;
r=p;
ch=getchar();
}
if(r!=Null) r->next=Null;
return head;
}
查找:按值查找
linklist *locate(head,k)
linklist *head;
elemtp k;
{linklist *s;
s=head->next;
while(s!=Null)
if(s->data!=k)
s=s->next;
else break;
return s; }
查找:按序号查找
linklist *Get(head,i);
linklist *head;
int i;
{int j;
linklist *p;
p=head;j=0;
while((p->next!=Null)&&(i>j))
{p=p->next;
j++;
}
if(i==j) return p;
else
return Null;
}
插入:
insert(p,x)/*将值为x的新结点插入*p之后*/
linklist *p;
elemtp x;
{linklist *s;
s=malloc(sizeof(linklist));
s->data=x;
s->next=p->next;
p->next=s;
}
void insert(head,x,k)/*在单链表中值为k的结点之前插入一个值为x的新结点*/
linklist *head;
int x,k;
{linklist *q,*p,*r;
r=malloc(sizeof(linklist));
r->data=x;
if(head->next==Null)
{head->next=r;
r->next=Null;
}
else
{q=head->next;
p=head->next->next;
while(p!=Null)
{if(p->data!=k)
{q=p;
p=p->next;}
else break;
if(p!=Null)
{q->next=r;
r->next=p;}
else
{q->next=r;
r->next=Null;}
}
}
}
删除:
delete(p) /*删除*p结点的后继*/
linklist *p;
{linklist *r;
r=p->next;
p->next=r->next;
free(r);}
linklist *delete(head,i)/*删除单链表head的第i个结点*/
linklist *head,*s;
int i;
{int j=0;
linklist *p,*q;
p=head;
while((p->next!=Null)&&(jnext;j++;}
if(p->next==Null)
{q=p->next;
p->next=p->next->next;
free(q);
}
else
return Null;
s=head;
return s;
} |