[英]Singly Linked List deleting last element
調用此函數時,整個列表將被刪除。 這是我的代碼。
head
是一個全局變量。 struct node
定義為Node
。
void delete_last() {
Node *temp = head, *prev;
if (temp->next != NULL) {
free(head);
head = NULL;
return;
} else {
while (temp->next != NULL) {
prev = temp;
temp = temp->next;
}
free(temp);
prev->next = NULL;
return;
}
}
有兩個問題:
if (temp->next == NULL)
head
或temp
之前測試列表是否為空。 這是修改后的版本:
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;
}
}
}
對於初學者,由於這些語句,如果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
您要釋放頭節點,並在錯誤的情況下將其設置為null。
if(temp->next!=NULL)
一開始應該是
if(temp->next==NULL)
如果下一個節點不為 null,則表示存在某些內容,而temp
不是最后一個元素。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.