有一个双向链表,将它所有的正数都加倍
比如1 2 -3 -4变为1 1 2 2 -3 -4
2条回答 默认 最新
- CSDN专家-天际的海浪 2021-12-28 04:43关注
你题目的解答代码如下:
#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"); }
如有帮助,请点击我的回答下方的【采纳该答案】按钮帮忙采纳下,谢谢!
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报
悬赏问题
- ¥15 python爬取bilibili校园招聘网站
- ¥30 求解达问题(有红包)
- ¥15 请解包一个pak文件
- ¥15 不同系统编译兼容问题
- ¥100 三相直流充电模块对数字电源芯片在物理上它必须具备哪些功能和性能?
- ¥30 数字电源对DSP芯片的具体要求
- ¥20 antv g6 折线边如何变为钝角
- ¥30 如何在Matlab或Python中 设置饼图的高度
- ¥15 nginx中的CORS策略应该如何配置
- ¥30 信号与系统实验:采样定理分析