有关链表的创建与简单 *** 作

有关链表的创建与简单 *** 作,第1张

有关链表的创建与简单 *** 作

目录

一、创建链表

1、定义链表

2、创建链表

3、输出链表

4、代码模板

二、简单 *** 作链表

1、链表排序

2、链表插入

3、链表合并


一、创建链表 1、定义链表

struct student{
    int score;
    struct student *next;
};

2、创建链表

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;//头结点的数据域是空的
}

3、输出链表

 head=head->next ;//如果头结点的数据域是空的
    while(head!=NULL) 
    {
        printf("%d ",head->ch);
        head = head->next;
    }    

4、代码模板
#include
#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;
}
二、简单 *** 作链表 1、链表排序

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;
}

2、链表插入

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;
}

3、链表合并

    p=head1->next ;

    while(p->next !=NULL)//将链表head1移到尾结点
    {
        p=p->next;
    }
    p->next =head2->next ;//将head2连接到head1的尾部

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5702820.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存