为什么主功能中没有打印链表?

时间:2019-04-13 09:10:28

标签: c list

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

> head(data$Date)
[[1]]
 [1] "2016-06-08" "2016-06-08" "2016-06-13" "2016-06-13" "2016-06-13" "2016-06-14"
 [7] "2016-06-14" "2016-06-14" "2016-06-14" "2016-06-14" "2016-06-14" "2016-09-15"
[13] "2016-10-31"

[[2]]
[1] "2016-10-02"

[[3]]
[1] "2016-09-25"

[[4]]
[1] "2017-02-16"

> data %>%
+     mutate(time1 = Date[[1]][1])%>%
+     select(time1)
# A tibble: 29,036 x 1
   time1     
   <chr>     
 1 2016-06-08
 2 2016-06-08
 3 2016-06-08
 4 2016-06-08
 5 2016-06-08
 6 2016-06-08

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

1 个答案:

答案 0 :(得分:1)

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

主要功能

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

}

SPOILER ALERT!

以上代码可能会导致内存泄漏!