首页 > 解决方案 > 为什么链表不在主函数中打印?

问题描述

这里在main函数中,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() 函数中打印新列表。为什么不打印?

标签: clist

解决方案


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

主功能

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

}

剧透警报!

以上代码可能存在内存泄漏!!!


推荐阅读