gpt4 book ai didi

c - 为什么主函数中不打印链表?

转载 作者:行者123 更新时间:2023-11-30 19:02:36 25 4
gpt4 key购买 nike

在主函数中,CreateList函数创建一个链接列表,Printlist函数打印该列表。

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

struct Node{
int Element;
struct Node *Next;
};
typedef struct Node *PtrToNode;

void PrintList( PtrToNode L ) {
PtrToNode P = L->Next;
printf("head -> ");

while( P != NULL ) {
printf("%d -> ", P->Element);
P = P->Next;
}
printf("NULL\n");
}

void Insert( int X, PtrToNode P ){
PtrToNode TmpCell = malloc( sizeof( struct Node ) );
TmpCell->Element = X;
TmpCell->Next = P->Next;
P->Next = TmpCell;
}

PtrToNode CreateList(int a[], int n){
int i;
PtrToNode header = malloc( sizeof( struct Node ) );
PtrToNode P= header;
header->Element = -1;
header->Next = NULL;

for(i=0; i<n; i++){
Insert(a[i], P);
P = P->Next;
}

return header;
}

void ReverseList( PtrToNode L1);

void main(){
int data1[]={3,18,7,21,4,14,10,8,12,17};

PtrToNode list = CreateList(data1, 10);

printf("original list: ");PrintList(list);
ReverseList(list);

printf("revsered list: ");PrintList(list);
}


void ReverseList( PtrToNode L1){
int i;
int array[10];

for(i=9; L1->Next != NULL; i--){
L1=L1->Next;
array[i]=L1->Element;
}

L1 = CreateList(array, 10);
printf("revsered list: ");PrintList(L1);

}

为了反转列表,我将元素复制到数组中并反转它。然后调用Createlist函数创建一个新的链表。那里没问题。它输出正确。但它应该在 Void main() 函数中打印新列表。为什么不打印?

最佳答案

要了解原因,让我们解决问题。

主要功能

void main(){
...
PtrToNode list = CreateList(data1, 10); // this will create the linked list and list will point to the list, let's say ** list contains the address x **.

...
ReverseList(list);// list is passed to the function, ** list has address x **

printf("revsered list: ");PrintList(list); // list is being printed again, ** what would list contains, ofcourse, x **.
}

反向函数

   void ReverseList( PtrToNode L1){ // L1 is pointing to list, so far so good.
...

L1 = CreateList(array, 10); // L1 is overitten with address of new list. Now L1 and list in main() are not same anymore.

printf("revsered list: ");PrintList(L1); // since L1 is new list i.e. a list created with reverse data, hence it gave the correct output. Thing to note here is that new reverse list L1 and old list(create in main()) has no link and they are independent list.
}

如何获得想要的结果?

主函数需要更改

void main(){
...
PtrToNode list = CreateList(data1, 10);

...
list = ReverseList(list); // Update the list pointer with the reverse list.
}

反向功能所需的更改

PtrToNode  ReverseList( PtrToNode L1); // change funtion to return a list pointer instead of being void.

PtrToNode ReverseList( PtrToNode L1){
...
L1 = CreateList(array, 10);
...
return L1; // return reverse list pointer

}

剧透警告!

以上代码存在内存泄漏问题!!!

关于c - 为什么主函数中不打印链表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55663832/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com