使用宣告結構initialize,traverse

使用宣告結構initialize(),traverse(),insert(),等函數實作單向鏈結串列,一一插入, ( data,structure ) ,再依反順序印出

Update:

要輸入data,structure這些字

再依反順序印出

1 Answer

Rating
  • 1 decade ago
    Favorite Answer

    #include <stdio.h>

    struct node {

    int val;

    struct node* next;

    };

    struct node *head;

    void initialize()

    {

    head = NULL;

    }

    void traverse_h(struct node *ptr)

    {

    if (ptr->next == NULL) {

    printf("%d\n",ptr->val);

    } else {

    traverse_h(ptr->next);

    printf("%d\n", ptr->val);

    }

    }

    void traverse()

    {

    traverse_h(head);

    }

    void insert( int v )

    {

    struct node *ptr, *tmp;

    if ( head == NULL ) {

    head = (struct node *) malloc( sizeof(struct node));

    head -> val = v;

    head -> next = NULL;

    } else {

    ptr = head;

    while (ptr -> next != NULL) {

    ptr = ptr-> next;

    }

    tmp = (struct node *) malloc( sizeof(struct node));

    ptr -> next = tmp;

    tmp -> val = v;

    tmp -> next = NULL;

    }

    }

    int main()

    {

    initialize();

    insert(5);

    insert(8);

    insert(6);

    insert(0);

    insert(9);

    insert(2);

    traverse();

    }

Still have questions? Get your answers by asking now.