要刪除雙向連結串列中指定資料之後節點,需要執行以下步驟。
temp
。temp = head;
while(temp -> data != val){
temp = temp -> next;
}
if(temp -> next == NULL)
{
return;
}
null
,以便它是連結串列新的最後一個節點。if(temp -> next -> next == NULL)
{
temp ->next = NULL;
}
ptr
指向要刪除的節點。 讓temp
節點的next
指標指向下一個ptr
。 使ptr
節點的下一個節點的前一個指向temp
。釋放ptr
指標。ptr = temp -> next;
temp -> next = ptr -> next;
ptr -> next -> prev = temp;
free(ptr);
演算法
第1步:IF HEAD = NULL
提示溢位
轉到第9步
[IF結束]
第2步:設定TEMP = HEAD
第3步:在TEMP - > DATA!= ITEM 時重複第4步
第4步:設定TEMP = TEMP - > NEXT
[迴圈結束]
第5步:SET PTR = TEMP - > NEXT
第6步:設定TEMP - > NEXT = PTR - > NEXT
第7步:SET PTR - > NEXT - > PREV = TEMP
第8步:釋放PTR
第9步:退出
示意圖
C語言實現範例程式碼 -
#include<stdio.h>
#include<stdlib.h>
void create(int);
void delete_specified();
struct node
{
int data;
struct node *next;
struct node *prev;
};
struct node *head;
void main()
{
int choice, item;
do
{
printf("1.Append List\\n2.Delete node\\n3.Exit\\n4.Enter your choice?");
scanf("%d", &choice);
switch (choice)
{
case 1:
printf("Enter the item\\n");
scanf("%d", &item);
create(item);
break;
case 2:
delete_specified();
break;
case 3:
exit(0);
break;
default:
printf("Please enter valid choice\\n");
}
} while (choice != 3);
}
void create(int item)
{
struct node *ptr = (struct node *)malloc(sizeof(struct node));
if (ptr == NULL)
{
printf("OVERFLOW\\n");
}
else
{
if (head == NULL)
{
ptr->next = NULL;
ptr->prev = NULL;
ptr->data = item;
head = ptr;
}
else
{
ptr->data = item;
ptr->prev = NULL;
ptr->next = head;
head->prev = ptr;
head = ptr;
}
printf("Node Inserted\\n");
}
}
void delete_specified()
{
struct node *ptr, *temp;
int val;
printf("Enter the value");
scanf("%d", &val);
temp = head;
while (temp->data != val)
temp = temp->next;
if (temp->next == NULL)
{
printf("Can't delete\\n");
}
else if (temp->next->next == NULL)
{
temp->next = NULL;
printf("Node Deleted\\n");
}
else
{
ptr = temp->next;
temp->next = ptr->next;
ptr->next->prev = temp;
free(ptr);
printf("Node Deleted\\n");
}
}
執行上面範例程式碼,得到以下結果 -
1.Append List
2.Delete node
3.Exit
4.Enter your choice?1
Enter the item
12
Node Inserted
1.Append List
2.Delete node
3.Exit
4.Enter your choice?1
Enter the item
23
Node Inserted
1.Append List
2.Delete node
3.Exit
4.Enter your choice?1
Enter the item
34
Node Inserted
1.Append List
2.Delete node
3.Exit
4.Enter your choice?2
Enter the value23
Node Deleted