【问题标题】:How move backwards in a linked list?如何在链表中向后移动?
【发布时间】:2013-02-15 08:06:06
【问题描述】:

假设我有字符串“Lamps”,它被传递到我的程序中,每个字符都存储到链表中的一个节点中。

我需要使用另一个链表以相反的顺序复制该列表,我该怎么做,我已经走了很远,但是如何在链表中向后移动?

您将看到注释了我需要放在那里以在链接列表中向后移动的内容。

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

struct NODE {
    struct NODE *next;  
    char data;

};


int main(int argc, char *argv[]) {

int i;

struct NODE *head;
struct NODE *current;
struct NODE *head2;
struct NODE *current2;
struct NODE *finger;


for(i = 0; i < argc; i++)
    printf("arg %d: %s\n", i, argv[i]);

head = (struct NODE*)malloc(sizeof(struct NODE));
    current = head;


    for ( i = 0; i < sizeof(argv[1]) - 1; i++ ) {

    current -> data = argv[1][i];
    current -> next = (struct node*)malloc(sizeof(struct NODE));
    current = current -> next;
    current -> next = NULL;

}


head2 = (struct NODE*)malloc(sizeof(struct NODE));
    current2 = head2;

    while ( current != head) {

        finger = head;


    while (finger -> next != current) 

        finger = finger -> next;
        current2 -> data = current -> data;
        current2 -> next = (struct node*)malloc(sizeof(struct NODE));
        current2 = current2 -> next;    
        // move backwards



    } // ends loop



}






return 0;

}

【问题讨论】:

    标签: c linked-list reverse


    【解决方案1】:

    如何在(单)链表中向后移动?

    你没有。将一个列表反转为另一个列表的技巧是在目标列表的头部而不是后面插入。您需要按照next 指针以常规方式遍历原始列表,而不是将元素添加到目标列表的末尾,而是创建一个新节点,并用它替换目标的标题。

    这是一个分步说明:

    sourceHead -> "A" -> "B" -> "C" -> NULL
    your pointer   ^
    targetHead -> NULL
    
    sourceHead -> "A" -> "B" -> "C" -> NULL
    your pointer          ^
    targetHead -> "A" -> NULL
    
    sourceHead -> "A" -> "B" -> "C" -> NULL
    your pointer                 ^
    targetHead -> "B" -> "A" -> NULL
    
    sourceHead -> "A" -> "B" -> "C" -> NULL
    your pointer                        ^
    targetHead -> "C" -> "B" -> "A" -> NULL
    

    【讨论】:

      【解决方案2】:

      简短的版本是使用 prev 变量扩展您的结构,当您创建一个孩子时,您将 self 分配给它的 Parent 变量,因此您可以稍后从孩子读取它的父变量以向后移动一个 - 并递归到一路走到顶峰。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-07-26
        • 2021-11-11
        • 2011-02-24
        • 2017-06-02
        • 1970-01-01
        相关资源
        最近更新 更多