题解 | #牛牛的双链表求和#
牛牛的双链表求和
https://www.nowcoder.com/practice/efb8a1fe3d1f439691e326326f8f8c95
#include <malloc.h> #include <stdio.h> /*int main() { int a, b; while (scanf("%d %d", &a, &b) != EOF) { // 注意 while 处理多个 case // 64 位输出请用 printf("%lld") to printf("%d\n", a + b); } return 0; }*/ /*typedef struct node { int data; struct node *next; }node; //创建头结点 node *createnode() { node *head=(node*)malloc(sizeof(node)); if(head==NULL) return NULL; head=head->next; return head; } //尾插 void insertnode(node *head,int data) { node *new=(node*)malloc(sizeof(node)); if(new==NULL) return; new->data=data; new->next=NULL; node *p=NULL; for(p=head;p->next!=head;p=p->next); new->next=p->next; p->next=new; } //打印 void output(node *head) { if(head->next==head) return; node *p=head->next; while(p!=head) { printf("%d",p->data); } } int mian() { int n; scanf("%d",&n); int a[n]; int i; for(i=0;i<n;i++) { scanf("%d",&a[i]); } node *head1=createnode();//头结点 for(int k=0;k<n;k++) { insertnode(head1, a[k]); } output(head1); return 0; }*/ #include <stdio.h> #include <stdlib.h> //单向循环链表 typedef struct node { int data; struct node *next; }node; //创建头节点 node *add_head() { node *Head = (node *)malloc(sizeof(node)); if(Head == NULL) return NULL; Head->next = Head; return Head; } //尾插法 void add_node(node *Head,int data) { node *new = (node*)malloc(sizeof(node)); if(new == NULL) return; //节点成员赋值 new->data = data; new->next = NULL; //链接 node *pT = NULL; for(pT = Head;pT->next != Head;pT = pT->next); new->next = pT->next; pT->next = new; } //输出链表 void output(node *Head1,node *head2) { if(Head1->next == Head1 && head2->next == head2) return; node *pT1 = Head1->next; node *pT2 = head2->next; //node *p=NULL; while(pT1 != Head1 && pT2 != head2) { //printf("%d ",pT->data); pT2->data += pT1->data; printf("%d ",pT2->data); pT1=pT1->next; pT2=pT2->next; } } int main(void) { node *Head1 = add_head();//头节点 node *Head2 = add_head();//头节点 int n,i,j,x,y; scanf("%d",&n); int a[n],b[n]; //将键盘键入的数据存放到数组中 for(i = 0;i < n;i++) scanf("%d",&a[i]); for(x = 0;x < n;x++) scanf("%d",&b[x]); //将数据插入链表 for(j = 0;j < n;j++) add_node(Head1, a[j]); for(y = 0;y < n;y++) add_node(Head2, b[y]); output(Head1,Head2); return 0; }