使用c将节点插入链表中的特定位置

时间:2019-08-17 18:28:16

标签: 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;
}

错误答案

您的输出(标准输出) 〜对stdout无响应〜

3 个答案:

答案 0 :(得分:1)

执行此操作((适用于hackerrank)

 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;

   int i=0;
    while((i!=position-1)
    {
        currentNode=currentNode->next;
        i++;
    }

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

return head;
 }

答案 1 :(得分:0)

这里

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

比较是不正确的,您正在将int类型与currentNode->next而不是int 对应,编译器应已警告您是否已使用正确的标志进行了编译,例如

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++;
}

答案 2 :(得分:0)

与其比较(currentNode->next) != position(在比较整数指针时没有意义),还应该限制在此位置跳过和插入的节点数。如果position太大,请注意在列表末尾停下来以插入末尾。

SinglyLinkedListNode *insertNodeAtPosition(SinglyLinkedListNode *head, int data, int position) {

    SinglyLinkedListNode *newNode = (SinglyLinkedListNode *)malloc(sizeof(SinglyLinkedListNode));
    if (newNode == NULL) {
        printf("out of memory\n");
        return head;
    }

    newNode->data = data;

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

    SinglyLinkedListNode *currentNode = head;

    while (currentNode->next != NULL && --position > 0) {
        currentNode = currentNode->next;
    }
    newNode->next = currentNode->next;
    currentNode->next = newNode;

    return head;
}