首页 > 解决方案 > 使用 c 在链表中的特定位置插入节点

问题描述

谁能告诉我哪里做错了。我是链表数据结构的新手,这是我的代码:

样本输入

3
16
13
7
1
2

样本输出

16 13 1 7

解释

初始链表是16 13 7。我们必须在当前位置插入。更新后的链表将是16 13 1 7

SinglyLinkedListNode *insertNodeAtPosition(SinglyLinkedListNode *head, int data, int position) {
    SinglyLinkedListNode *newNode = (SinglyLinkedListNode *)malloc(sizeof(SinglyLinkedListNode));
    newNode->data = data;

    if (head == NULL) {
        return newNode;
    }

    if (position == 0) {
        newNode->next = head;
        return newNode;
    }

    SinglyLinkedListNode *currentNode = head;

    while ((currentNode->next) != position) {
        currentNode = currentNode->next;
    }

    newNode->next = currentNode->next;
    currentNode->next = newNode;

    return head;
}

错误的答案

你的输出(标准输出)~标准输出没有响应~

标签: c

解决方案


这里

while((currentNode->next)!=position) {}

比较是不正确的,你是与不是的comapringint类型currentNode->nextint,编译器应该警告你是否已经使用适当的标志编译,如

gcc -Wall -Wextra -pedantic -Werroc test.c

试试这个版本

int itr = 0; 
while(currentNode != NULL && itr < position) { /* iterate till position & until currentNode not NULL. both condition must satisfy */
    currentNode=currentNode->next;
    itr++;
}

推荐阅读