zoukankan      html  css  js  c++  java
  • 单链表的插入操作的实现(0952)SUWST-OJ

     Description

    建立长度为n的单链表,在第i个结点之前插入数据元素data。

    Input

    第一行为自然数n,表示链式线性表的长度;第二行为n个自然数表示链式线性表各元素值;第三行为指定插入的位置i;第四行为待插入数据元素data。

    Output

    指定插入位置合法时候,输出插入元素后的链式线性表的所有元素,元素之间用一个空格隔开。输入不合法,输出“error!”。

     
    Sample Input
    5
    1 2 3 4 5
    3
    6
    Sample output
    1 2 6 3 4 5
     
    代码:


    #include<stdio.h>
    #include<stdlib.h>
    int total;
    typedef struct node
    {
    int data;
    struct node * next;
    }Node;
    void Create(Node*&L,int a[],int n)//尾插法
    {
    Node *s,*r;
    int i;
    L=(Node*)malloc(sizeof(struct node));
    r=L;
    for(i=0;i<n;i++)
    {
    s=(Node*)malloc(sizeof(struct node));
    s->data=a[i];
    r->next=s;
    r=s;
    }
    r->next=NULL;
    }
    void input(Node*&L)//输入函数
    {
    int a[1000];
    int i;
    scanf("%d",&total);
    for(i=0;i<total;i++)
    {
    scanf("%d",&a[i]);
    }
    Create(L,a,total);
    }
    bool Add(Node*L,int i,int e)//判断以及寻找要插入的位置
    {
    if(i>total)
    {
    return false;
    }
    int j=0;
    Node *p,*q;
    p=L;
    while(j<i-1&&p)
    {
    j++;
    p=p->next;
    }
    if(p==NULL)
    return false;
    else
    {
    q=(Node*)malloc(sizeof(struct node));
    q->data=e;
    q->next=p->next;
    p->next=q;
    return true;
    }
    }

    void output(Node*L)//输出函数
    {
    Node *read;
    read=L->next;
    while(read->next)
    {
    printf("%d ",read->data);
    read=read->next;
    }
    printf("%d",read->data);
    }
    int main()
    {
    int i;
    Node*L;
    input(L);
    scanf("%d",&i);
    int e;
    scanf("%d",&e);
    if(Add(L,i,e))
    {
    output(L);
    }
    else
    printf("error!");
    return 0;
    }

     
  • 相关阅读:
    正点原子的串口助手XCOM V2.0编码问题
    切图设计工具软件或平台
    Notepad++插件
    emWin调用GUI_PNG_Draw方法显示PNG图片
    C语言-结构体冒号(:)位域
    Keil报错:error: #130: expected a "{"
    Doxygen简明注释语法
    Ubuntu连接不上Xshell
    Springboot注解的作用
    idea常用快捷键
  • 原文地址:https://www.cnblogs.com/FENGXUUEILIN/p/4397942.html
Copyright © 2011-2022 走看看