2-4 递增链表的插入 链表

2-4

《数据结构学习与实验指导》书中的例题,感觉难度小一点,
mooc中的题目一下子难度好大,慢慢来吧,写了这题有点理解链表了。

#include<stdio.h>
#include<string.h>
#include<math.h>
#include<algorithm>
#include<iostream>
using namespace std;

typedef struct node *nodeptr;
//链表结点的数据结构
struct node
{
    int val;
    nodeptr next;
};

int main()
{
    int i,n,m;
    nodeptr head,tmp,rear,pre;//head 头结点 tmp 临时结点 rear 最后的一个结点 pre 当前节点
    //设置空结点
    head=rear=(nodeptr)malloc(sizeof(struct node));//开辟链表
    head->next=NULL;//设指针为空
    scanf("%d%d",&n,&m);

        for(i=0;i<n;i++)//创建链表
        {
            pre=(nodeptr)malloc(sizeof(struct node));//申请新结点
            pre->next=NULL;
            scanf("%d",&pre->val);
            rear->next=pre;
            rear=pre;
        }
        //寻找m插入的结点
        pre=head;
        while(pre->next!=NULL&&pre->next->val<m)
            pre=pre->next;

        //插入m结点
        tmp=(nodeptr)malloc(sizeof(struct node));
        tmp->val=m;
        tmp->next=pre->next;
        pre->next=tmp;

        //新结点是在表尾时,要改变rear值
        if(pre=rear) rear=tmp;

        //输出答案
        tmp=head->next;
             printf("%d",tmp->val);
        for(tmp=tmp->next;tmp!=NULL;tmp=tmp->next)
        {
            printf(" %d",tmp->val);
        }
        printf("
");
    return 0;
}

版权声明:本文为博主原创文章,未经博主允许不得转载。http://xiang578.top/

原文地址:https://www.cnblogs.com/xryz/p/4848056.html