【问题标题】:Insert element at specific position, single concatenated list在特定位置插入元素,单个连接列表
【发布时间】:2020-06-11 17:19:58
【问题描述】:

我的任务是用 C 编写一个函数。这个函数应该如下工作:

int insert_pos(int v, int pos, list * l)

功能是在位置pos插入一个值为v的新列表元素到列表l中。列表头元素的位置始终为 0。 如果 pos 不是列表 l 中的位置,则该函数应返回 -1,否则返回 0。 这是一个串联的列表。

不幸的是,我没有真正的方法来做到这一点。

我很高兴你的帮助!

【问题讨论】:

  • 您好,欢迎来到 StackOverflow! list 是什么?
  • 没有初始化列表,只定义了。
  • 我的意思是,list 是什么类型?
  • 整数列表
  • 那么,typedef int list;?

标签: c list function


【解决方案1】:

您可以使用 string.h 中的 memmove 进行简单插入。 memmove,顾名思义,将一块内存从一个位置移动到另一个位置,即使两个区域重叠。所以,

memmove(l+pos+1,l+pos,(lengh_of_list-pos)*sizeof(int));

您现在可以插入值:

l[pos] = value;

警告:您需要担心列表是否足够大以包含附加值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-24
    • 1970-01-01
    • 1970-01-01
    • 2022-10-17
    • 1970-01-01
    • 2021-04-23
    • 2014-03-30
    • 1970-01-01
    相关资源
    最近更新 更多