我寫了一個包含鏈接列表的簡單程序。當我嘗試在創建的函數中顯示鏈表時,它工作正常;但是,當我返回到主並嘗試顯示它時,它不能正常工作。鏈接列表的頭部在傳遞給函數時發生變化
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <iostream>
#define LEN 20
struct Node {
char word[LEN];
int count;
Node * next;
};
Node* build_linked_list (char array[][LEN], int N);
Node* make_ordered_copy (Node * head);
void print_list(Node * head);
int main()
{
#define NUMBER 10
char array[NUMBER][LEN]; // array which the words will be recorded
int N=6;
for(int a=0; a<N; ++a) strcpy(array[a], "test");
print_list(build_linked_list(array, N));
getchar();
return 0;
}
Node* build_linked_list (char array[][LEN], int N)
{
Node ndArray[N];
Node *head, *newnode;
head = &ndArray[0];
strcpy(head->word, array[0]); // writing the first element to the head
head->count = 0;
head->next = NULL;
for(int a=1; a<N; ++a) // writing the elements in a linked list
{
newnode = &ndArray[a];
strcpy(newnode->word, array[a]);
newnode->count = 0;
newnode->next = head; // first location now becomes second location
head = newnode;
}
print_list(head);
printf("Previous values were shown in build_linked_list\n");
return head;
}
void print_list(Node* head)
{
Node* traverse;
traverse = head;
while(traverse) // while traverse is not NULL
{
printf("\"%s\" with the frequency of %d\n", traverse->word, traverse->count);
traverse = traverse->next;
}
return;
}
當從主叫print_list功能調試,「traverse->字」表示在第一次正確的值,但它不打印正確,然後將其更改爲一些其他值。
好的,非常感謝。當我第一次寫這部分時,我曾經想過,但不知怎的,我已經確信自己會沒事的:D。現在它工作正常,再次感謝。 – bgun 2013-03-24 21:25:48