C语言 这段代码有什么问题?



我正在为删除双向链表的最后一个节点而写作。但是,每次当我在列表中有 2 个或超过 2 个元素时,这个函数都会给我分段错误。

void deleteEnd()
{
struct node *ptr;
if(head==NULL)
printf("nList is empty.First add some numbers");
else if(head->next==NULL)
{
head = NULL;
free(head);
}
else
{
ptr = head;   
while(ptr->next != NULL)  
{  
ptr = ptr -> next;   
}  
ptr -> prev -> next = NULL;   
free(ptr);  
}
}

通常,当您从链表中删除节点时,最好将对列表第一个节点的引用作为函数的参数传递。在您的情况下,您没有向我们显示头部的来源,我认为这可能是一个非常有用的信息,我敢打赌错误隐藏在那里。

这就是实现的样子:

#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *next;
};
// insert end node: this is for testing purposes
struct node *insertEnd(struct node *head, int value) {
struct node *ptr, *new_node;
ptr = head;
new_node = (struct node *) malloc(sizeof(struct node));
new_node->data = value;
new_node->next = NULL;
// The list is empty
if (head == NULL) {
head = new_node;
return head;
}
// Non empty list
while (ptr->next != NULL) {
ptr = ptr->next;
}
ptr->next = new_node;
return head;
}
// delete end node
struct node *deleteEnd(struct node *head) {
struct node *ptr, *preptr;
ptr = head;
preptr = NULL;
// The list is empty
if (head == NULL) {
printf("The list is empty. Nothing to delete.n");
return head;
}
while(ptr->next != NULL) {
preptr = ptr;
ptr= ptr->next;
}
free(ptr);
if (preptr == NULL) {
head = NULL;
}
else {
preptr->next = NULL;
}
return head;
}
int main(void) {
struct node *llist;
llist = NULL;
llist = insertEnd(llist, 10);
llist = insertEnd(llist, 20);
llist = insertEnd(llist, 30);
llist = deleteEnd(llist);
llist = deleteEnd(llist);
llist = deleteEnd(llist);
return 0;
}

维护一个全局变量头并在每次推送/弹出后更新它总是一个好主意。看到这个:

struct node
{
int data;
struct node *next;
};
struct node *start = NULL;
struct node *deleteEnd(struct node *start)
{
struct node *ptr = start;
if(ptr==NULL)
{
printf("nList is empty!!!");
return start;
}
else if(ptr->next == NULL)
{
free(ptr);
start = NULL;
return start;        
}
else
{
while((ptr->next)->next!=NULL)      //by doing this you dont have to maintain a prev pointer
{
ptr=ptr->next;
}
struct node *temp = ptr->next;
free(temp);
ptr->next = NULL;
return start;

}
}

希望这有帮助!!

相关内容

  • 没有找到相关文章