【发布时间】:2020-05-12 06:56:53
【问题描述】:
这个程序应该删除单链表中的 N 节点。如果我输入 N = 1 或 N = 2 没关系,程序可以工作。但是当 N = 0 时,输出会打印出具有随机值的无限节点(在删除节点 0 之后)。我认为程序看不到新的头部。谢谢帮忙!
#include <stdio.h>
#include <stdlib.h>
#define N 0
struct node {
int data;
struct node *next;
};
void printlist(struct node *head){
struct node *current=head;
int i=0;
while (current!=NULL){
printf("node number %d \t : %d\n", i, current->data);
current=current->next;
i++;
}
}
int deletenode(struct node *head,int n){
struct node *current=head;
struct node *previous=head;
int i=0;
while(current!= NULL){
if (n==i && i!=0){
previous->next=current->next;
free(current);
return 1;
}
else if (n==i && i==0){
head=head->next;
free(current);
return 1;
}
i++;
previous=current;
current=current->next;
return 0;
}
printf("error\n");
exit(EXIT_FAILURE);
}
void main(){
struct node *n1=malloc(sizeof(struct node));
struct node *n2=malloc(sizeof(struct node));
struct node *n3=malloc(sizeof(struct node));
struct node *head=n1;
n1->data=5;
n1->next=n2;
n2->data=10;
n2->next=n3;
n3->data=15;
n3->next=NULL;
printf("\n\nbefore\n");
printlist(head);
deletenode(head,N);
printf("\n\nafter\n");
printlist(head);
}
我使用current作为临时指针,因为在第二个节点上的磁头移位后,我需要一个指向旧磁头的指针并免费使用。
【问题讨论】:
-
deletenode 应该返回一个指向新头的指针
标签: c pointers struct linked-list singly-linked-list