删除链表 C 编程中的某个节点



我的代码中不断出现分段错误,但我不知道为什么。 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
    }
}

首先,in都不会在循环中更新,因此它将继续移动到下一个节点,因此最终会出现分段错误。

您可以尝试更改原始循环:

while (i < n-1) {
    current = current->next;    //node before deleted node.
}

到以下内容:

while (i < n-1) {
    current = current->next;    //node before deleted node.
    i++;
}

相关内容

  • 没有找到相关文章

最新更新