不带头结点的链表,其插入和删除节点操作需要分两种讨论:第一个数据节点 和 非第一个数据节点。
加入了一个不含数据项的头结点可以统一这两个操作,使得插入和删除可以统一实现,避免了分情况讨论。
#ifndef LIST2_H_INCLUDED
#define LIST2_H_INCLUDEDtypedef int ElemType;
struct node
{
ElemType data;
struct node*next;
};
struct node* InitialList(struct node*head)/*链表的初始化*/
{
head = (struct node*)malloc(sizeof(struct node));
head -> next = NULL;
return head;
}
int length(struct node*head)
{
int len=0;
for(len=0;head->next;head=head->next) len++;
return len;
}
struct node*Insert(struct node*head,int position,ElemType x)
{
if(position<1||position>length(head)+1)
{
printf("illegal position.\n");
return head;
}
int k;
struct node*p=head;
struct node*tmp=(struct node*)malloc(sizeof(struct node));
tmp->data = x;
for(k=1;k<position;k++) p=p->next;
tmp->next = p->next;
p->next = tmp;
return head;
}
void Print(struct node*head)
{
if(head->next==NULL) printf("List is empty.\n");
else printf("List has %d elements.They are:\t",length(head));
while(head->next)
{
printf("%d\t",head->next->data);
head = head->next;
}
printf("\n");
}
struct node*DelNode(struct node*head,ElemType x)
{
if(head->next==NULL)
{
printf("Can't Delete.List is empty.\n");
return head;
}
struct node*p,*tmp;
for(p=head;p->next;p=p->next)
{
if(p->next->data==x) break;
}
if(p->next==NULL) //未找到
{
printf("No this Element.\n");
return head;
}
tmp = p->next;
p->next = tmp->next;
free(tmp);
return head;
}
#endif // LIST2_H_INCLUDED