题解 | #牛牛的双链表求和#
牛牛的双链表求和
https://www.nowcoder.com/practice/efb8a1fe3d1f439691e326326f8f8c95
#include <stdio.h> #include <stdlib.h> //声明结构体 struct List { int date; struct List* next; }; //新节点 struct List* BuyNewCode(int x) { struct List* new=(struct List*)malloc(sizeof(struct List)); new->date=x; new->next=NULL; return new; } //尾插(不带头) void PushBack(struct List** pplist,int x) { struct List* new=BuyNewCode(x); if(*pplist==NULL) { *pplist=new; } else { //用于寻找尾节点的指针 struct List* tail=*pplist; while(tail->next!=NULL) { tail=tail->next; } //找到,链接新节点 tail->next=new; } } //相加 void AddList(struct List* plist1,struct List** pplist2) { struct List* tail1=plist1; struct List* tail2=*pplist2; while(tail1!=NULL && tail2!=NULL) { tail2->date=tail1->date+tail2->date; tail1=tail1->next; tail2=tail2->next; } } //打印输出 void Print(struct List* plist) { struct List* cur=plist; while(cur!=NULL) { printf("%d ",cur->date); cur=cur->next; } } int main() { int n=0; scanf("%d",&n); //不带头指针的链表 struct List* plist=(struct List*)malloc(sizeof(struct List)); struct List* plist2=(struct List*)malloc(sizeof(struct List)); plist=NULL; plist2=NULL; int i=0; int k=0; for(i=0;i<n;i++) { scanf("%d",&k); PushBack(&plist,k); } for(i=0;i<n;i++) { scanf("%d",&k); PushBack(&plist2,k); } AddList(plist,&plist2); Print(plist2); return 0; }