OJ《程序设计基础II》实验2——链表

2-1 A - 数据结构实验之链表一:顺序建立链表

#include<stdio.h>
#include<string.h>
typedef struct Node//typedef使用后,下面的结构体可不用struct
{
    int data;
    struct Node *next;
}node;
node *creat(int n)
{
    node *head,*p,*tail;
    head=(node*)malloc(sizeof(node));//malloc函数,建立一个头节点;
    head->next=NULL;//头节点指向空;
    tail=head;//尾节点指向空;
    for(int i=0;i<n;i++)
    {
        p=(node*)malloc(sizeof(node));//建立一个新的节点p;
        scanf("%d",&p->data);//给节点p赋值;
        p->next=NULL;//p指向空;
        tail->next=p;//让tail指向p;
        tail=p;//将p代替tail的位置进行循环,可以实现将新的p顺序加到链表中;
    }//顺序建链表;
    return head;
}
int main()
{
    node *head,*p;
    int n;
    scanf("%d",&n);
    head=creat(n);//顺序建链表;
    p=head->next;//遍历链表;
    while(p)//也可以写while(p!=NULL)
    {
        if(p->next==NULL)
            printf("%d",p->data);
        else printf("%d ",p->data);
        p=p->next;
    }//输出;
    return 0;
}

2-2 B - 数据结构实验之链表二:逆序建立链表

#include <stdio.h>
#include <stdlib.h>
typedef struct Node
{
    int data;
    struct Node *next;
}node;
node *creat(int n)
{
    node *head,*p;
    head=(node*)malloc(sizeof(node));
    head->next = NULL;//和顺序一样;
    for(int i=0;i<n;i++)
    {
        p=(node*)malloc(sizeof(node));
        scanf("%d",&p->data);
        p->next=head->next;//让p指向head所指的;
        head->next=p;//让head指向p,实现将p逆序建立链表。
    }
    return head;
}
 
int main()
{
    int n;
    scanf("%d",&n);
    node *head,*p;
    head=creat(n);
    p=head->next;
    while(p)
    {
        if(p->next==NULL)
        printf("%d",p->data);
        else printf("%d ",p->data);
        p=p->next;
    }
    return 0;
}
 

2-3 C - 师--链表的结点插入

#include <stdio.h>
#include <stdlib.h>
typedef struct Node
{
    int data;
    struct Node *next;
}node;
void Insert(node *head,int m,int x)//执行插入操作的函数
{
    node *q=(node *)malloc(sizeof(node)),*p=head;
    q->data=x;//准备好新节点并赋值
    for(int i=0;i<m&&p->next!=NULL;i++)//查找第m个,但如果p->next==NULL也要结束循环
    {
        p=p->next;//建立链表往后走
    }
    q->next=p->next;//将q插入找到的位置
    p->next=q;
}
int main()
{
    int n;
    while(~scanf("%d",&n))
    {
        node *head,*p;
        head=(node*)malloc(sizeof(node));
        head->next&#
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

CRAEN

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值