目录
一、创建链表
1、定义链表
2、创建链表
3、输出链表
4、代码模板
二、简单 *** 作链表
1、链表排序
2、链表插入
3、链表合并
一、创建链表 1、定义链表
2、创建链表struct student{
int score;
struct student *next;
};
3、输出链表struct student *creat(int n){
struct student *head,*end;//定义头节点,尾部节点;
end =head = (struct student*)malloc(sizeof(struct student));//分配地址
for (int i = 0; i < n; i++)
{
struct student *node;//定义一个普通结点
scanf("%d",&node->score);//给普通节点数据域赋值
end->next = node;//连接
end = node;//移位 *** 作
}
end->next = NULL;//结束创建
return head;//头结点的数据域是空的
}
4、代码模板head=head->next ;//如果头结点的数据域是空的
while(head!=NULL)
{
printf("%d ",head->ch);
head = head->next;
}
#include二、简单 *** 作链表 1、链表排序#include struct student{ int score; struct student *next; }; struct student *creat(int n){ struct student *head,*end;//定义头节点,尾部节点; end =head = (struct student*)malloc(sizeof(struct student));//分配地址 for (int i = 0; i < n; i++) { struct student *node;//定义一个普通结点 scanf("%d",&node->score);//给普通节点数据域赋值 end->next = node;//连接 end = node;//移位 *** 作 } end->next = NULL;//结束创建 return head;//头结点的数据域是空的 } int main() { int n; struct student *head1; scanf("%d",&n); head1=creat(n); head1=head1->next ; while(head1!=NULL)//输出链表 { printf("%d ",head1->ch); head1 = head1->next; } return 0; }
2、链表插入struct node *fun(struct node *head,int n)//冒泡排序
{
struct node *p,*q;
p=q=head->next ;
int temp;
for(int j=0;j{
for(int i=0;i{
if(p->ch > p->next->ch)
{
temp=p->ch;
p->ch=p->next->ch;
p->next->ch=temp;
}
p=p->next;//指向下一个结点
}
q=q->next;
p=q;
}
return head;
}
3、链表合并struct node *fun(struct node *head,int n)//将第一个结点删除并插入表中适当位置
{
struct node *previous,*current,*key;
key=head->next ; //记录插入结点(第一个结点)
current=head->next->next ; //当前结点(从第二个开始)
head=current; //首结点后移(第二个变成第一个,以此类推)
if(current->ch>=key->ch)//如果线性表本来就有序
{
return key;
}
while(current!=NULL&¤t->ch<=key->ch)//找到比第一个结点大的结点
{
previous=current;//记录要找结点的前一个结点
current=current->next;
}
if(current==NULL) //结点均不大于首结点,将插入结点挂在表尾
{
previous->next= key;
key->next = NULL;
}
else //将第一个结点插入在previous和current之间
{
previous->next=key;
key->next=current;
}
return head;
}
p=head1->next ;
while(p->next !=NULL)//将链表head1移到尾结点
{
p=p->next;
}
p->next =head2->next ;//将head2连接到head1的尾部
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)