c - 删除链表中给定位置的节点

标签 c pointers linked-list singly-linked-list

给定一个单向链表和一个位置,我试图删除特定位置的链表节点。 代码:

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

struct node
{
    int data;
    struct node* next;
};

void printList(struct node* head_ref)
{
    //struct node* head_ref = (struct node*)malloc(sizeof(struct node));

    if(head_ref == NULL)
    printf("The list is empty");

    while(head_ref!=NULL)
    {
        printf("%d\n",head_ref->data);
        head_ref = head_ref->next;  
    }
}

void insert_beg(struct node **head_ref,int new_data)
{
    struct node* new_node = (struct node*)malloc(sizeof(struct node));
    new_node->data = new_data;
    new_node->next = *head_ref;
    *head_ref = new_node;
}

void delete(struct node **head_ref,int position)
{
    int i=1;
    if(*head_ref == NULL)
    return;

    struct node *tails,*temp = *head_ref;
    if(position == 0)
    {

        *head_ref = temp->next;
        free(temp);
        return;
    }

    while(temp->next!=NULL)
    { 
        tails = temp->next;
        temp = temp->next;

        if(i == position)
        {
            tails->next = temp->next;
            free(temp);
            return;     
        }

        i++;
    }

}

int main()
{
    struct node *head = NULL;
    insert_beg(&head,36);
    insert_beg(&head,35);
    insert_beg(&head,34);
    insert_beg(&head,33);

    printList(head);
    int position;
    printf("Enter the position of the node u wanna delete\n");
    scanf("%d",&position);

    delete(&head,position);
    printf("\n");
    printList(head);
}

每当我尝试删除位置 0 以上的节点时,我在该特定位置得到的是 0,而不是什么都没有。我能知道我哪里出错了吗? 例如我的名单是:33 34 35 36 我的输出:33 0 35 36(尝试删除节点 1 时) 有效输出:33 35 36

最佳答案

问题是因为这个错误的语句导致的

while(temp->next!=NULL)
{ 
    tails = temp->next;
    ^^^^^^^^^^^^^^^^^^^
    temp = temp->next;

在这种情况下,tails 和 temp 是相同的节点。如果删除了 temp,则将已删除节点的数据成员 next 设置为 temp->next

    if(i == position)
    {
        tails->next = temp->next;
        ^^^^^^^^^^^^^^^^^^^^^^^^^

这里tails是要删除的节点。

您应该更改被删除节点之前的节点的下一个数据成员。所以错误的语句应该像这样更新

while(temp->next!=NULL)
{ 
    tails = temp;
    ^^^^^^^^^^^^^
    temp = temp->next;

至于我,那么我会按照下面的方式编写函数

int delete( struct node **head, size_t position )
{
    struct node *prev = NULL;

    size_t i = 0;

    while ( i != position && *head != NULL ) 
    {
        prev = *head;
        head = &( *head )->next;
        ++i;
    }

    int success = *head != NULL;

    if ( success )
    {
        struct node *tmp = *head;

        if ( prev == NULL )
        {
            *head = ( *head )->next;
        }
        else
        {
            prev->next = ( *head )->next;
        }

        free( tmp );
    }

    return success;
}   

关于c - 删除链表中给定位置的节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38659066/

相关文章:

c - 尝试用c重写realloc函数

c - execvp() 系统调用未执行

c - C中的冒泡排序通用实现

c++ - 从二进制文件中检索数据,无意义的字符

C: Enqueue() - 在链表末尾插入,返回链表头

c - 我想开始嵌入式设备编程(如果像我这样的人可能的话)

c - PDF:如何找到渲染时文本占用多少空间?

c - 在函数中将数组声明为静态的目的是什么?

c++ - 向指针数组添加元素

java - 如何制作有序链表?