有一个双向链表,将它所有的正数都加倍
比如1 2 -3 -4变为1 1 2 2 -3 -4
你题目的解答代码如下:
#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");
}
如有帮助,请点击我的回答下方的【采纳该答案】按钮帮忙采纳下,谢谢!
我用#CSDN#这个app发现了有技术含量的博客,小伙伴们求同去《详解双向链表的基本操作(C语言)》, 一起来围观吧 https://blog.csdn.net/qq_16933601/article/details/105351119?utm_source=app&app_version=4.21.0&code=app_1562916241&uLinkId=usr1mkqgl919blen
这里面有例子,代码完整