我试图弄清楚如何操作链表。我想删除给定链表的结束节点并将其添加到另一个给定链表的末尾。
出于某种原因,我无法正确地指出我的指针,好吧——至少我认为问题出在哪里。
(此方法位于 while 循环中,因此一个列表不断变小,而另一个列表不断增长。)
void movenode(struct Node **cards,struct Node **column)
{
struct Node *head = NULL;
struct Node *tmp,*head1 = *cards;
struct Node *tmp2,*head2 = *column;
if (*cards == NULL || (*cards)->next == NULL){
return;
}
while (tmp->next != NULL) {
head->next = tmp;
tmp = tmp->next;
}
while (tmp2->next != NULL) {
tmp2 = tmp2->next;
}
head->next = NULL;
tmp2->data = tmp;
tmp2->next = NULL;
*cards = head1;
*column = head2;
}
希望有人能够帮助我更好地理解这一点。
出于某种原因,我无法正确指出我的指针,嗯.. 至少这是我认为问题所在。
你是对的,但它不止于此。例如,在struct Node *head = NULL;
没有修改 中的值之后head
,因此每次您都head->next
在“NULL + 一个小偏移量”处访问内存(并且可能会崩溃)。
要从单链表中删除最后一个条目,您必须找到最后一个条目之前的条目(以便您可以修改它next
);并且要将条目添加到链接列表中,您必须找到最后一个条目(以便您可以修改其next
)。考虑到这一点,我们可以将其分为 5 个部分:
进行完整性检查
*cards
查找列表中最后一个条目之前的条目
删除列表中的最后一个*cards
条目
查找列表中的最后一个*column
条目
将(删除的)条目添加到*columns
列表的末尾
您可以一次实现这 5 个部分中的每一个(并对其进行测试)。这是编程的一个重要部分——将更复杂的东西分解成更简单的东西。
生成的代码可能类似于(未经测试):
void movenode(struct Node **cards,struct Node **column) {
struct Node *temp = *cards;
struct Node *removed;
// Do sanity checks
if (temp == NULL) {
return;
}
// Find the entry before the last entry in the `*cards` list
if(temp->next != NULL) {
while(temp->next->next != NULL) {
temp = temp->next;
}
}
// Remove the last entry in the `*cards` list
if(temp == NULL) {
// The last entry was the first entry
removed = temp;
*cards = NULL;
} else {
removed = temp->next;
temp->next = NULL;
}
// Find the last entry in the `*column` list
temp = *column;
if(temp != NULL) {
while(temp->next != NULL) {
temp = temp->next;
}
}
// Add the (removed) entry to the end of the `*columns` list
if(temp == NULL) {
// There was no last entry (list was empty)
*column = removed;
} else {
temp->next = removed;
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句