gpt4 book ai didi

c - 如何在链表中向后移动?

转载 作者:太空狗 更新时间:2023-10-29 16:02:17 25 4
gpt4 key购买 nike

假设我有字符串“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;

}

最佳答案

How do I move backwards in the (singly) linked list ?

你不知道。将一个列表反转为另一个列表的技巧是在目标列表的头部而不是后面插入。您需要按照 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

关于c - 如何在链表中向后移动?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15147286/

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