【问题标题】:C Insert Element Into List At Given IndexC在给定索引处将元素插入列表
【发布时间】:2015-04-12 22:16:29
【问题描述】:

我有一个 C 语言编程问题,我正在尝试设计一个列表并在给定索引处添加一个元素。

这是我的 insertElement 方法:

ListElement* getNextElement(ListElement *listElement){
    return listElement->nextElement;
}

 /* Insert a given element at the specified index in a specified list. Shifts
 *  all other elements to the right, increasing their index by 1. 
 *  Requires 0 <= index <= listSize(), otherwise the element should not be inserted.  
 */
void insertElement(List *list, ListElement *listElement, int index) {
    ListElement* tempElement = list->headElement;
    int count = 0;
    while (tempElement != NULL) {
        if (count == index) {
        }
        tempElement = getNextElement(tempElement);
        count++;
    }
}

但我实际上并不知道如何移动和插入元素。

这是我尝试插入的方式:

int main() {
    ListElement* newElement = malloc(sizeof(ListElement));
    insertElement(&myList, newElement, 1);
    exit(EXIT_SUCCESS);
}

谁能帮帮我?提前致谢。

【问题讨论】:

  • 索引和列表听起来很奇怪。马修给你一些提示

标签: c list insert element


【解决方案1】:

链表的美妙之处在于,与数组不同,您无需移动或移动任何东西即可进行插入。

假设您的列表是A-&gt;C,并且您想在A 之后插入B 以提供A-&gt;B-&gt;C

  • A-&gt;nextElement 设置为C;这需要改变。
  • B-&gt;nextElement 未设置;这需要改变。

你应该能够看到如何用你所得到的来完成它。

【讨论】:

  • if (count == (index - 1)) { setNextElement(listElement);类似的东西?唯一的问题是我不知道如何将 listElement 的下一个元素设置为我当前所在的元素之后的第二个元素。如果这有任何意义..
  • @Nic listElement-&gt;nextElement = tempElement-&gt;nextElement; tempElement-&gt;nextElement = listElement;。在我的示例中,这适用于 B-&gt;next = A-&gt;next; A-&gt;next = B;,相当于 B-&gt;next = C; A-&gt;next = B;
  • 嗯,我得到了一些有趣的输出。该函数添加了元素,但似乎添加了指针地址。 LIST: 8, 9, 10, 11, 12 添加后 LIST: 8, 9, 135364624, 10, 11, 12
猜你喜欢
  • 2020-08-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-01
  • 2013-01-31
相关资源
最近更新 更多