【问题标题】:How do I join two linked lists in C?如何在 C 中加入两个链表?
【发布时间】:2013-06-24 15:30:42
【问题描述】:

我想完成两个链接列表以准备考试 这是我到目前为止所拥有的 1 - 反转链表中的元素 2 - 将 list2 附加到列表一的末尾

我在课程中从某人那里获得了反向功能的帮助,并试图注释掉每个步骤以了解发生了什么,但我很挣扎。如果你也可以帮助我,那就太棒了

在组合功能中,我只是整体感到困惑 什么时候用'&',什么时候用'*'?

typedef struct node *list;

typedef struct node {
    int   value;
    list  whateverNextIsCalled;
} node;

// Reverse list
list reverse (list inputList){
    list outputList = NULL;

    while (inputList != NULL) {

       /*
        nodePtr points to the first element in the inputList
        */
        node *nodePtr = inputList;

       /* 
        Make the head pointer of inputList point to the next element
        */
        inputList = inputList->whateverNextIsCalled;

       /*
        ???? help point 1
        */
        nodePtr->whateverNextIsCalled = outputList;

       /*
        ???? help point 2
        */
        outputList = nodePtr;
    }
    return outputList;
}

// Add one list to the end of another
void combine (list list1, list list2){

   /*
    Point to the first value of list1 
    */
    node *current = list1;

   /*
    Find the last node of list1
    */
    while(current->whateverNextIsCalled != NULL) {
        current = current->whateverNextIsCalled;
    }
    //connect the last node of toList and the first node of fromList
    current->whateverNextIsCalled = &list2;

    list1 = current;
}    

【问题讨论】:

    标签: linked-list append


    【解决方案1】:

    你可以到达第一个链表的最后一个,然后在它的下一个将有 null 的地方放下一个链表的开头

    我不太明白你为什么把名单倒了

    【讨论】:

    • 我有一个实践考试,我们会被告知要编写一个反向/追加/添加函数......所以我只是在练习
    • 我该如何写出来呢?我真的不明白这个话题
    • 查看每个列表,如果它不是一个循环列表,那么它的结束节点下一个地址必须有 NULL,所以如果你想添加任何列表,那么只需放置一些类似的东西,假设我正在运行第一个列表的循环,请确保您像while(p->next)而不是(while(p)一样运行循环,在第一种情况下它将在最后一个节点停止,您可以说p->next = secondList(起始地址第二个列表),现在如果你像while(p)一样运行循环,那么它将在NULL上停止,所以你将无法将地址存储在NULL中,因为它不会是一个节点,它只是一个NULL
    • 类似地,如果你想反转然后做同样的事情,如果它的双链表,意味着如果它包含下一个地址以及上一个地址,那么你可以到达末端节点,然后遍历prev 地址,但如果它是单个链接列表,那么您必须采用交换逻辑,
    • 如果你想追加,那么在你必须追加之前停止一个点,并在你停止的节点中插入新地址,然后在新节点中添加你停止的下一个节点的地址:- )
    猜你喜欢
    • 1970-01-01
    • 2021-12-24
    • 1970-01-01
    • 2015-07-06
    • 2011-10-21
    • 2018-12-17
    • 2015-04-28
    • 2021-07-23
    • 1970-01-01
    相关资源
    最近更新 更多