我的代码中一直存在分段错误,但我不知道为什么。 int n
是我要删除的节点。所以listDeleteNth(new, 2)
将删除序列中的3。
1→2→3→4
1→2→4
typedef struct _node *Node;
typedef struct _list *List;
typedef struct _list {
Node head;
} list;
typedef struct _node {
int value;
Node next;
} node;
void listDeleteNth (List l, int n) {
Node current = l->head;
int i = 0;
while (i < n-1) {
current = current->next; //node before deleted node.
}
Node temp = current->next; //make temp the one to be deleted.
if (current->next->next == NULL) {
printf("you deleted the last node!\n"); //check if dlting lastnode
} else {
current->next = current->next->next; //connect prev to after
}
}
答案 0 :(得分:0)
首先,i
和n
都没有在循环中更新,因此它将继续移动到下一个节点,从而最终出现分段错误。
您可以尝试更改原始循环:
while (i < n-1) {
current = current->next; //node before deleted node.
}
以下内容:
while (i < n-1) {
current = current->next; //node before deleted node.
i++;
}