您的位置:首页 > 编程语言 > C语言/C++

C语言中关于链表的一些操作

2017-06-13 12:27 465 查看
struct data
{int num;
struct data *next;
};

/* 创建链表 */
struct data *creat()
{struct data *head=NULL,*p,*q;
p=q=malloc(sizeof(struct data));
scanf("%d",&p->num);
while(p->num)
{if(head==NULL)
head=p;
else
{q->next=p;
q=p;
}
p=malloc(sizeof(struct data));
scanf("%d",&p->num);
}
q->next=NULL;
return head;
}

/* 插入结点 */
struct data *insert(struct data *head,int num)
{struct data *p,*q;
p=malloc(sizeof(struct data));
p->num=num;
if(p->num<head->num)
{p->next=head;
head=p;
}
else
{q=head;
while(q->next&&p->num>q->next->num)
q=q->next;
p->next=q->next;
q->next=p;
}
return head;
}

/* 删除结点 */
struct data *del(struct data *head,int num)
{struct data *p;
if(num==head->num)
head=head->next;
else
{p=head;
while(p->next&&num!=p->next->num)
p=p->next;
if(p->next)
p->next=p->next->next;
}
return head;
}

/* 链表反序 */
struct data *invert(struct data *head)
{struct data *p=head,*q=NULL;
while(p)
{head=p;
p=p->next;
head->next=q;
q=head;
}
return head;
}

/* 输出链表 */
void print(struct data *head)
{while(head)
{printf("%d ",head->num);
head=head->next;
}
printf("\n");
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: