题解 | #牛牛的链表删除#

牛牛的链表删除

http://www.nowcoder.com/practice/d3df844baa8a4c139e103ca1b1faae0f

#include <stdio.h>
#include <stdlib.h>

typedef struct ListNode
{
    int data;
    struct ListNode *next;
} ListNode;

struct ListNode * createList(int arr[], int n, int index)
{
    struct ListNode *ptr;

    if (index == n)
        return NULL;

    ptr = (struct ListNode *) malloc(sizeof *ptr);
    ptr->data = arr[index];
    ptr->next = createList(arr, n, index + 1);

    return ptr;
}

struct ListNode * del(struct ListNode *head, int x)
{
    struct ListNode *tmp;

    if (head == NULL)
        return NULL;

    head->next = del(head->next, x);
    if (head->data != x)
        return head;

    tmp = head->next;
    free(head);

    return tmp;
}

void travel(struct ListNode *head, 
            void (*visit) (int))
{
    while (head)
    {
        visit(head->data);
        head = head->next;
    }
}

static void visit(int data)
{
    printf("%d ", data);
}

int main(int argc, const char *argv[])
{
    int i;
    int n, x;
    struct ListNode *head;

    if (scanf("%d%d", &n, &x) != 2)
        exit(EXIT_FAILURE);

    int arr[n];

    for (i = 0; i < n; ++i)
        scanf("%d", arr + i);

    head = createList(arr, n, 0);
    head = del(head, x);

    travel(head, visit);

    return 0;
}
全部评论

相关推荐

10-22 19:18
上海大学 后端
jopajhhdjwnqk:水印都叠杀人书了
点赞 评论 收藏
分享
评论
1
1
分享
牛客网
牛客企业服务