//定义结构体,以链表中元素为int为例
struct node{
int data;
struct node *next;
};
struct node* Insert(struct node*head,int element)//相同的,插到后面
{
//findprevious and insert element after the position found;
struct node* t=head;
while(t->next!=NULL&&t->next->data<=element)
t=t->next;
struct node *p;
p=(struct node*)malloc(sizeof(struct node));
p->data=element;
p->next=t->next;
t->next=p;
return head;
};
struct node* Delete(struct node *head,int element)//删第一个element
{
//findprevious and delete the element after the position found;
struct node* t=head;
while(t->next!=NULL&&t->next->data!=element)
t=t->next;
if(t!=NULL){
struct node* p;
p=t->next;
t->next=p->next;
free(p);
}
return head;
};
void Print(struct node* head)
{
struct node* t = head->next;
while(t!=NULL){
printf("%d\n",t->data);
t=t->next;
}
}
int main(){
//申请表头
struct node *head;
head=(struct node *)malloc(sizeof(struct node));
head->next=NULL;
//插入元素
head=Insert(head,10);//以10为例
//删除元素
head=Delete(head,6);//以6为例
//遍历元素
Print(head);
}
线性表的链式实现(单链表)——有独立表头的实现
最新推荐文章于 2023-05-09 23:11:27 发布