c - C中的单链表:pushBack
问题描述
我必须创建将元素添加到列表末尾的 pushBack 方法,但它实现的 pushBack 方法不起作用。下面我留下代码:
#include <stdio.h>
#include <stdlib.h>
typedef struct
{
int *data;
struct Node *next;
}Node;
typedef struct
{
// Puntero al primer nodo
Node *head;
// Cantidad de datos
unsigned short size;
// Puntero al ultimo dato accedido.
Node *current;
}List;
List *createList();
Node *createNode(int *);
void pushBack(List *, int *);
int main(void)
{
List *lista = createList();
pushBack(&lista, 4);
return 0;
}
List *createList()
{
List *list = (List *) malloc(sizeof(List));
list -> head = NULL;
list -> size = 0;
list -> current = NULL;
return list;
}
Node *createNode(int *data)
{
Node *node = (Node *) malloc(sizeof(Node));
node -> data = data;
node -> next = NULL;
return node;
}
// Función para insertar un nuevo nodo al final de la lista
void pushBack(List *list, int *data)
{
Node *node = createNode(data);
while ( list -> head )
list -> head = list -> head -> next;
list -> head = node;
list -> size ++;
}
pushBack 方法中的任何更正将不胜感激。
解决方案
关于您当前的代码:
void pushBack(List *list, int *data)
{
Node *node = createNode(data);
while ( list -> head )
list -> head = list -> head -> next;
list -> head = node;
list -> size ++;
}
只有在列表之前为空的情况下,将某些内容推到列表的后面才应该改变头部。您所做的实际上是通过将其头部移动到不应该的位置来破坏列表。
您可能打算使用current
而不是head
(head
当然在第一次将其设置为之后),但在列表本身中为该字段指定一个字段是不寻常的 - 您通常只使用一个临时变量。
您最好也存储尾巴,这样您就不必每次都搜索它(a)。但是,假设这不是一个选项,下面的伪代码应该可以帮助你:
def push_back(list, item):
# Force tail constraints, new tail must be end of list.
item.next = null
# If list empty, simply set head.
if list.head == null:
list.head = item
return
# Find last element in list:
curr = list.head
while curr.next != null:
curr = curr.next
# Now have last, just attach new item to it.
curr.next = item
将其转换为 C,我将留给读者作为练习。你应该至少做一些功课:-)
(a)如果您对如何执行此操作感兴趣,请参见下文:
def push_back(list, item):
# Force tail constraints, new tail must be end of list.
item.next = null
# If list empty, simply set head/tail.
if list.head == null:
list.head = item
list.tail = item
return
# In non-empty list, tail will always be last element.
curr.tail.next = item # Point current tail to new tail.
curr.tail = item # Update tail
推荐阅读
- python - 尝试在预训练模型上进行预测时出现“此估计器是否拟合”错误
- mysql - 在 SQL PSQL 或 SQL 服务器中按不同类型组合字符串
- javascript - 在 Web 组件中使用外部 CSS 链接引用
- javascript - Koloboks 的简单统计计算器
- node.js - 使用 express.js 上传图片
- javascript - 反应本机webview | 3Ds 安全性不重定向页面
- actions-on-google - 为什么助手会特意打断我的动作?
- toit - 无法从流中接收数据
- java - 当超类有私有方法时调用接口的默认方法
- python - 如果我在服务器上运行脚本,我应该设置虚拟环境吗?