我写了一个代码,用于添加和删除双链表。首先,我按顺序添加元素并打印,它就可以工作了。然后我删除元素,并考虑不在列表中的元素;找不到号码";。关于其他元素我只能删除300个其他元素不能删除。问题出在哪里?
#include<stdio.h>
#include<stdlib.h>
//Doubly Linked List
struct n{
int x;
struct n * next;
struct n * prev;
};
typedef struct n node;
void print(node * r){
while(r!=NULL){
printf("%d ", r->x);
r=r->next;
}
printf("n");
}
node * addSeq(node * r, int x){
if(r==NULL){//if linkedlist is empty, makes a node and puts an element
r=(node *)malloc(sizeof(node));
r->next=NULL;
r->prev=NULL;//as well as next prev must point to NULL
r->x=x;
return r;
}
if(r->x > x){//if not empty but less than first element root changes
node * temp = (node *)malloc(sizeof(node));
temp->x = x;
temp->next=r;
r->prev=temp;
return temp;
}
node * iter = r;
while(iter->next!=NULL && iter->next->x < x){
iter=iter->next;
}
node * temp = (node *)malloc(sizeof(node));
temp->next = iter->next;
iter->next=temp;
temp->prev=iter;
if(temp->next!=NULL)
temp->next->prev=temp;
temp->x=x;
return r;
}
node * delete(node *r, int x){
node *temp;
node *iter = r;
if(r->x == x){
temp = r;
r = r->next;
free(temp);
return r;
}
while(iter->next != NULL && iter->next->x != x){
iter = iter->next;
}
if(iter->next==NULL){
printf("Number was not found n");
return r;
}
temp = iter->next; //iter points to the element that is previous of the element which we want
//to delete
iter->next = iter->next->next;
iter->next->prev=iter;//temp is the element that we want to delete
free(temp);
return r;
}
int main(){
node * root;
root = NULL;
root=addSeq(root, 400);
root=addSeq(root, 350);
root=addSeq(root, 500);
root=addSeq(root, 450);
root=addSeq(root, 300);
print(root);
root=delete(root, 410);
print(root);//Cannot find number and prints the elements
root=delete(root, 300);
print(root);
root=delete(root, 500);
print(root);
root=delete(root, 350);
print(root);
}
当要删除的节点不是列表中的第一个时,执行以下代码:
temp = iter->next; //iter points to the element that is previous of the element which we want
//to delete
iter->next = iter->next->next;
iter->next->prev=iter;//temp is the element that we want to delete
考虑一下当这个节点iter->next
是列表中的最后一个时会发生什么。则iter->next->nexzt
为空,并且iter->next = iter->next->next;
将iter->next
设置为空。然后iter->next->prev
尝试取消引用该空指针。
您必须更改代码处理列表中最后一个节点的方式。