题解 | 牛牛的双链表求和

牛牛的双链表求和

https://www.nowcoder.com/practice/efb8a1fe3d1f439691e326326f8f8c95

#include <stdio.h>
#include <stdlib.h>
#define N 100

struct Node
{
    int data;
    struct Node *next;
};

struct Node* createList(int *arr,int n)
{
    struct Node *head = NULL, *tail = NULL;
    for(int i = 0; i < n; i++)
    {
        struct Node *newNode = (struct Node*)malloc(sizeof(struct Node));
    newNode -> data = arr[i];
    newNode -> next = NULL;
    if(head == NULL)
    {
        head = newNode;
        tail = newNode;
    }
    else 
    {
        tail -> next = newNode;//让当前最后一个节点的指针域,指向新创建的节点。
        tail = newNode;//将尾指针更新为新的节点
    }
    }

    return head;
}

void addList(struct Node *bhead,struct Node *ahead)
{
   struct Node *p = ahead, *q = bhead;
   while(p != NULL && q != NULL)
   {
    q -> data += p -> data;
    p = p -> next;
    q = q -> next;
   }
}
void printList(struct Node *head)
{
    struct Node *p = head;
    while(p != NULL)
    {
        printf("%d ",p -> data);
        p = p -> next;
    }
}
int main()
{
    int n;
    scanf("%d",&n);

    int arrA[N],arrB[N];

    for(int i = 0; i < n; i++)
    {
        scanf("%d",&arrA[i]);
    }

    for(int i = 0; i < n; i++)
    {
        scanf("%d",&arrB[i]);
    }

    struct Node *ahead = createList(arrA,n);
    struct Node *bhead = createList(arrB,n);

    addList(bhead,ahead);

    printList(bhead);

    return 0;
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务