我正在尝试将选定元素(节点)从链接列表移动到此列表的末尾。
struct* move(struct* list , struct* element)
{
while(list->next != NULL)
{
list = list->next;
}
list = element;
return list;
}
首先,结构element
是list
的一部分,但我需要将它移到最后。然而,他的表现似乎在起作用......
答案 0 :(得分:1)
当您执行list = element;
时,实际上list
指向element
并且不会更改您的列表。
您想要做的是:
list->next = element;
element->next = NULL;
但您仍需要从之前的位置移除element
。 move()
的样本就是:
struct struct_type * move(struct struct_type * list , struct struct_type * element) {
while (list->next != NULL) {
if (list->next == element)
list->next = list->next->next;
list = list->next;
}
list->next = element;
element->next = NULL;
return list;
}
如评论中所述,您必须指定列表的结构类型。
另请注意,返回list
会返回列表中的最后一个元素(我不认为这是预期的行为)。
编辑:处理第一个元素并返回列表的顶部元素。
struct struct_type * move(struct struct_type * list , struct struct_type * element) {
struct struct_type *l = list; //keeps reference to the list
if (l == NULL)
return l;
if (l == element)
list = l->next;
while (l->next != NULL) {
if (l->next == element)
l->next = l->next->next;
l = l->next;
}
l->next = element;
element->next = NULL;
return list;
}
答案 1 :(得分:0)
#include <stdio.h>
struct node {
char name;
struct node *next;
};
struct node *move(struct node *list, struct node *element){
struct node *head = list;
struct node *prev = NULL, *curr = head;
if(list == NULL || list->next == NULL)
return head;
while(curr){
if(curr == element){
if(curr == head){
head = curr->next;
} else {
prev ->next = curr->next;
}
curr = curr->next;
} else {
prev = curr;
curr = curr->next;
}
}
prev->next = element;
element->next = NULL;
return head;
}
void print(struct node *list);
int main(void) {
struct node a[] = {
{'A', NULL},
{'B', NULL},
{'C', NULL},
{'D', NULL},
{'E', NULL}
}, *head;
a[0].next = &a[1];
a[1].next = &a[2];
a[2].next = &a[3];
a[3].next = &a[4];
print(head=a);//A->B->C->D->E
head = move(head, head);
print(head);//B->C->D->E->A
head = move(head, &a[2]);
print(head);//B->D->E->A->C
head = move(head, &a[2]);
print(head);//B->D->E->A->C
return 0;
}
void print(struct node *list){
while(list){
printf("%c", list->name);
list = list->next;
if(list)
printf("->");
}
printf("\n");
}