gpt4 book ai didi

c - 为什么我不能在此链表的索引 0(头)处插入新节点?

转载 作者:行者123 更新时间:2023-12-04 05:01:04 25 4
gpt4 key购买 nike

代码:

/*
* File: problem5.c
* Author: levihackwith
* Description: Write a Pop() function that is the inverse of Push(). Pop() takes a non-empty list, deletes the head node, and returns the head node's data.
*/

#include <stdio.h>
#include <stdlib.h>

struct node { // Our custom node data type
int data;
struct node *next;
};

/*
* Adds a node to a linked list.
*
* This method was taken from the Appendix of the LinkedListProblems.pdf file from Stanford University.
*/
void Push(struct node** headRef, int newData) {
struct node* newNode = malloc(sizeof (struct node)); // allocate node
newNode->data = newData;
newNode->next = (*headRef);
(*headRef) = newNode;
};

void InsertNth(struct node** headRef, int insertAt, int newData) {
struct node* newNode = malloc(sizeof (struct node)); // allocate node
struct node* current = *headRef;
int index = 0;

newNode->data = newData;

while (current != NULL) {
if (insertAt == 0 && index == 0) {
newNode->next = (*headRef);
(*headRef) = newNode;
current = *headRef;
printf("Current's data is now %d at index %d \n\n", current->data, index);
} else {
if (index == (insertAt - 1)) {
printf("I inserted %d at index %d \n", newData, insertAt);
newNode->next = current->next;
current->next = newNode;
}
}
current = current->next;
index++;
}
}

/*
* Builds a linked list of a given size.
*/
struct node* BuildList(int numNodes) {
struct node* head = NULL; // Start with the empty list
int i;

for (i = numNodes; i >= 1; i--) {
Push(&head, i); // Use Push() to add all the data
}
return (head);
};

int main(void) {

struct node* myLinkedList;
struct node* current;
int currentIndex = 0;
int valToInsert = 45;
int insertIndex = 0;

myLinkedList = BuildList(5);
current = myLinkedList;

InsertNth(&myLinkedList, insertIndex, valToInsert);
while (current != NULL) {
printf("The value at index %d is %d \n", currentIndex, current->data);
currentIndex++;
current = current->next;
}

return 0;
};

输出
Current's data is now 45 at index 0

The value at index 0 is 1
The value at index 1 is 2
The value at index 2 is 3
The value at index 3 is 4
The value at index 4 is 5

上面的输出是当插入新值的索引为零时。这是在索引 1 处插入时的输出。
I inserted 45 at index 1

The value at index 0 is 1
The value at index 1 is 45
The value at index 2 is 2
The value at index 3 is 3
The value at index 4 is 4
The value at index 5 is 5

如您所见,0 不能按预期工作,而 1 可以。我究竟做错了什么?

最佳答案

What am I doing wrong?



您正在设置 current在调用 InsertNth 之前.当您调用 InsertNth插入 0 , myLinkedList会改变,所以 current将指向第二个节点。

移动 current = myLinkedList;InsertNth 之后打电话解决问题:
myLinkedList = BuildList(5);
InsertNth(&myLinkedList, insertIndex, valToInsert);
current = myLinkedList;

关于c - 为什么我不能在此链表的索引 0(头)处插入新节点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16137638/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com