使用宣告結構initialize,traverse

2009-04-02 7:02 pm
使用宣告結構initialize(),traverse(),insert(),等函數實作單向鏈結串列,一一插入, ( data,structure ) ,再依反順序印出
更新1:

要輸入data,structure這些字 再依反順序印出

回答 (1)

2009-04-03 6:39 am
✔ 最佳答案
#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();
}


收錄日期: 2021-05-02 12:02:08
原文連結 [永久失效]:
https://hk.answers.yahoo.com/question/index?qid=20090402000010KK02547

檢視 Wayback Machine 備份