我正试图将所选元素(节点)从链接列表移动到此列表的末尾。
struct* move(struct* list , struct* element)
{
while(list->next != NULL)
{
list = list->next;
}
list = element;
return list;
}
首先,结构体element
是list
的一部分,但我需要将它移到末尾。然而,他的doenst似乎在工作。。。
当您执行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
会返回列表中除一个元素之外的最后一个元素(我认为这不是预期的行为)。
EDIT:处理第一个元素并返回列表的顶部元素。
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;
}
#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");
}