删除循环链表时的垃圾值

时间:2015-05-24 15:57:49

标签: c linked-list

删除循环链表中节点的结构和功能如下:

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

    struct node *head = NULL;

void add(int n)
{
    struct node *temp=NULL,*trav=head;
    temp = (struct node*)malloc(sizeof(struct node));
    temp->data = n;
    if(head == NULL)
    {
        temp->next = temp;
        head = temp;
        return;
    }
    while(trav->next!=head)
        trav = trav->next;
    trav->next = temp;
    temp->next = head;
}

void delete(int x)
{
    struct node *temp=head,*rem=NULL;
    if(head!=NULL)
    {
        if(head->data==x)
        {
            while(temp->next!=head)
                temp = temp->next;
            rem=head;
            head = head->next;
            temp->next = head;
            free(rem);
        }
        else
        {
            while(temp->data!=x)
            {
                rem = temp;
                temp = temp->next;
            }
            rem->next = temp->next;
            free(temp);
        }
    }
    else
        printf("List is empty");
}

void print()
{
    struct node *temp=head;
    if(head==NULL)
    {
        printf("List is empty");
        return;
    }
    printf("\n The List is: ");
    do
    {
        printf(" %d ",temp->data);
        temp = temp->next;
    }while(temp!=head);
}

主函数调用如下所示:

int main(void)
{
    add(1);
    add(2);
    add(3);
    add(4);
    add(5);
    print();
    delete(1);
    delete(2);
    delete(3);
    delete(4);
    delete(5);
    print();
}

输出:

enter image description here

删除所有节点,但最后打印一个垃圾值。我的功能出了什么问题?

1 个答案:

答案 0 :(得分:1)

当您的列表变空时,即删除列表中的最后一个元素时,您需要设置head = NULL;

一个简单的修复可能是替换:

void delete(int x)
{
    struct node *temp=head,*rem=NULL;
    if(head!=NULL)
    {
        if(head->data==x)

使用:

void delete(int x)
{
    struct node *temp=head,*rem=NULL;
    if(head!=NULL)
    {
        if(head==head->next && head->data==x)
        {
            free(head);
            head=NULL;
        }
        else if(head->data==x)

我实际上并没有这样做,所以我可能没有涵盖所有案例。