单个链接列表删除最后一个元素

时间:2017-09-19 17:10:27

标签: c linked-list singly-linked-list

调用此函数时,将删除整个List。这是我的代码。

$categories是一个全局变量。 head定义为struct node

Node

3 个答案:

答案 0 :(得分:2)

有两个问题:

  • 第一次测试应为if (temp->next == NULL)
  • 在取消引用headtemp之前,您应该测试列表是否为空。

以下是修改后的版本:

void delete_last(void) {
    if (head != NULL) {
        Node *prev = NULL;
        Node *temp = head;
        while (temp->next != NULL) {
            prev = temp;
            temp = temp->next;
        }
        free(temp);
        if (prev) {
            prev->next = NULL;
        } else {
            head = NULL;
        }
    }
}

答案 1 :(得分:2)

对于初学者,由于这些陈述head等于NULL,该函数具有未定义的行为

Node *temp = head, *prev;

if (temp->next != NULL) {

此外,带有子语句的if语句在逻辑上是不正确的。

该功能可以按以下方式查看

void delete_last() 
{
    if ( head )
    {
        Node **last = &head;

        while ( ( *last )->next ) last = &( *last )->next;

        free( *last );
        *last = NULL;
    }
}

这是一个示范程序

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

typedef struct node
{
    int value;
    struct node *next;
} Node;

Node *head;

int push_front( int value )
{
    Node *new_node = malloc( sizeof( Node ) );
    int success = new_node != NULL;

    if ( success )
    {
        new_node->value = value;
        new_node->next = head;
        head = new_node;
    }

    return success;
}

void delete_last() 
{
    if ( head )
    {
        Node **last = &head;

        while ( ( *last )->next ) last = &( *last )->next;

        free( *last );
        *last = NULL;
    }
}

void output()
{
    for ( Node *current = head; current; current = current->next )
    {
        printf( "%d ", current->value );
    }
}

int main(void) 
{
    const int N = 10;

    for ( int i = 0; i < N; i++ )
    {
        push_front( i );
        output();
        putchar( '\n' );
    }

    while ( head )
    {
        delete_last();
        output();
        putchar( '\n' );
    }

    return 0;
}

它的输出是

0 
1 0 
2 1 0 
3 2 1 0 
4 3 2 1 0 
5 4 3 2 1 0 
6 5 4 3 2 1 0 
7 6 5 4 3 2 1 0 
8 7 6 5 4 3 2 1 0 
9 8 7 6 5 4 3 2 1 0 
9 8 7 6 5 4 3 2 1 
9 8 7 6 5 4 3 2 
9 8 7 6 5 4 3 
9 8 7 6 5 4 
9 8 7 6 5 
9 8 7 6 
9 8 7 
9 8 
9 

答案 2 :(得分:1)

您正在释放头节点并在错误的条件下将其设置为null。

if(temp->next!=NULL)

一开始应该是

if(temp->next==NULL)

如果下一个节点为null,则表示存在某些内容且temp不是最后一个元素。

相关问题