寂寞梧桐221 2021-12-28 00:38 采纳率: 60%
浏览 33
已结题

C语言双向链表类型例子

有一个双向链表,将它所有的正数都加倍
比如1 2 -3 -4变为1 1 2 2 -3 -4

  • 写回答

2条回答 默认 最新

  • 关注

    你题目的解答代码如下:

    #include <stdio.h>
    #include <stdlib.h>
    typedef struct line{
        struct line * prior;
        int data;
        struct line * next;
    }line;
    
    line* initLine(line * head,int a[], int n);
    line * insertLine(line * head,int data,int add);
    line * delLine(line * head,int data);
    void display(line * head);
    int main() {
        int a[] = {1,2,-3,-4,5};
        line * head=NULL;
        head=initLine(head, a,5);
        display(head);
        line * temp=head;
        int i = 0;
        while (temp) {
            i++;
            if (temp->data>0)
                head=insertLine(head, temp->data,i++);
            temp=temp->next;
        }
        display(head);
    
        return 0;
    }
    line* initLine(line * head,int a[], int n){
        head=(line*)malloc(sizeof(line));
        head->prior=NULL;
        head->next=NULL;
        head->data=a[0];
        line * list=head;
        for (int i=1; i<n; i++) {
            line * body=(line*)malloc(sizeof(line));
            body->prior=NULL;
            body->next=NULL;
            body->data=a[i];
    
            list->next=body;
            body->prior=list;
            list=list->next;
        }
        return head;
    }
    line * insertLine(line * head,int data,int add){
        //新建数据域为data的结点
        line * temp=(line*)malloc(sizeof(line));
        temp->data=data;
        temp->prior=NULL;
        temp->next=NULL;
        //插入到链表头,要特殊考虑
        if (add==1) {
            temp->next=head;
            head->prior=temp;
            head=temp;
        }else{
            line * body=head;
            //找到要插入位置的前一个结点
            for (int i=1; i<add-1; i++) {
                body=body->next;
            }
            //判断条件为真,说明插入位置为链表尾
            if (body->next==NULL) {
                body->next=temp;
                temp->prior=body;
            }else{
                body->next->prior=temp;
                temp->next=body->next;
                body->next=temp;
                temp->prior=body;
            }
        }
        return head;
    }
    
    //输出链表的功能函数
    void display(line * head){
        line * temp=head;
        while (temp) {
            printf("%d ",temp->data);
            temp=temp->next;
        }
        printf("\n");
    }
    

    img

    如有帮助,请点击我的回答下方的【采纳该答案】按钮帮忙采纳下,谢谢!

    img

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 1月5日
  • 已采纳回答 12月28日
  • 创建了问题 12月28日

悬赏问题

  • ¥15 python爬取bilibili校园招聘网站
  • ¥30 求解达问题(有红包)
  • ¥15 请解包一个pak文件
  • ¥15 不同系统编译兼容问题
  • ¥100 三相直流充电模块对数字电源芯片在物理上它必须具备哪些功能和性能?
  • ¥30 数字电源对DSP芯片的具体要求
  • ¥20 antv g6 折线边如何变为钝角
  • ¥30 如何在Matlab或Python中 设置饼图的高度
  • ¥15 nginx中的CORS策略应该如何配置
  • ¥30 信号与系统实验:采样定理分析