假设我有一个字符串"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: %sn", 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;
}
如何在(单)链表中向后移动?
你不。将一个列表反转到另一个列表的技巧是在目标列表的头部插入,而不是在后面插入。您需要通过遵循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
简短的版本是用prev变量扩展你的结构,当你创建一个子变量时,你将self赋值给它的父变量,这样你就可以稍后,从子变量中读取它的父变量向后移动一个-然后递归得到所有的方式到顶部