Verwenden der typedefinitions:Array zur Liste in C (iterativ)
typedef struct Node *List;
typedef struct Node {
int item;
List next;
} Node;
Die rekursive Lösung, die ich gefunden:
List arrayToList(int arr[],int n,int idx) {
if (n==idx) return NULL;
List list=malloc(sizeof(Node));
list->next=arrayToList(arr,n,idx+1);
list->item=arr[idx];
return list;
}
UPDATE: Das Folgende ist fast richtig, aber ich weiß nicht, warum Am Ende wird eine Null gedruckt.
List newNode() {
List li=malloc(sizeof(Node));
return li;
}
List arrayToList(int arr[],int n) {
List li=newNode();
List li1=li; /*save the beginning of the list*/
int i;
for (i=0;i<n;i++) {
li->item=arr[i];
li->next=newNode();
li=li->next;
}
li=NULL;
return li1;
}
void printList(List li) {
while (li!=NULL) {
li=li->next;
}
printf("\n");
}
int main(int argc, char* argv[]) {
int arr[]={4,1,2,3,4,7,4,5,6,8};
List li=arrayToList(arr,10);
printList(li);
return 0;
}
Der Ausgang, den ich bekomme, ist: 4 1 2 3 4 7 4 5 6 8 0.
UPDATE 2: Ändern der Funktion drucke in diese gibt mir korrekte Ausgabe:
void printList(List li) {
while (li->next!=NULL) {
printf("%d ",li->item);
li=li->next;
}
printf("\n");
}
Aber ich, warum sollte ich li->next!=NULL
als Wache frage mich übrig?
"Ich frage mich". Teile deine Gedanken. –
Sie sollten 'li-> next! = NULL 'haben, da das letzte Element in Ihrer Liste auf null zeigt. –