Linux循环链表删除节点,删除循环单链表开头元素
要刪除循環(huán)單鏈表中的開頭節(jié)點,需要進行一些指針調(diào)整。
在開頭有三種從循環(huán)單鏈表中刪除節(jié)點的方案有以下幾種。
情況1 :(鏈表為空)
如果鏈表為空,則條件head == NULL將變?yōu)閠rue,在這種情況下,只需要在屏幕上打印下溢并退出。
if(head == NULL)
{
printf("UNDERFLOW\n");
return;
}
情況2 :(鏈表包含單個節(jié)點)
如果鏈表只包含一個節(jié)點,則條件head->next == head將變?yōu)閠rue。 在這種情況下,需要刪除整個鏈表并使頭指針空閑。 這將通過使用以下語句來完成。
if(head->next == head)
{
head = NULL;
free(head);
}
情況3 :(鏈表包含多個節(jié)點)
如果鏈表包含多個節(jié)點,那么在這種情況下,需要使用指針ptr遍歷鏈表以到達列表的最后一個節(jié)點。 這將通過使用以下語句來完成。
ptr = head;
while(ptr -> next != head){
ptr = ptr -> next;
}
在循環(huán)結(jié)束時,指針ptr指向鏈表的最后一個節(jié)點。 因為,鏈表的最后一個節(jié)點指向鏈表的頭節(jié)點。 因此,這將改變?yōu)楝F(xiàn)在,鏈表的最后一個節(jié)點將指向頭節(jié)點的下一個節(jié)點。
ptr->next = head->next;
現(xiàn)在,通過使用C語言中的free()函數(shù)釋放頭指針。
free(head);
使節(jié)點指向最后一個節(jié)點的下一個節(jié)點,即鏈表的新頭。
head = ptr->next;
這樣,節(jié)點將從一開始就從循環(huán)單鏈表中刪除。
算法
第1步:IF HEAD = NULL
提示內(nèi)存溢出
轉(zhuǎn)到第8步
[IF結(jié)束]
第2步:設置PTR = HEAD
第3步:在PTR->NEXT!= HEAD 時重復第4步
第4步:SET PTR = PTR->next
[循環(huán)結(jié)束]
第5步:設置PTR->NEXT = HEAD->NEXT
第6步:免費頭
第7步:SET HEAD = PTR->NEXT
第8步:退出
示意圖
C語言實現(xiàn)代碼
#include
#include
void create(int);
void beg_delete();
struct node
{
int data;
struct node *next;
};
struct node *head;
void main()
{
int choice, item;
do
{
printf("1.Append List\n2.Delete Node from beginning\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:
beg_delete();
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));
struct node *temp;
if (ptr == NULL)
{
printf("OVERFLOW");
}
else
{
ptr->data = item;
if (head == NULL)
{
head = ptr;
ptr->next = head;
}else
{
temp = head;
while (temp->next != head)
temp = temp->next;
ptr->next = head;
temp->next = ptr;
head = ptr;
}
printf("Node Inserted\n");
}
}
void beg_delete()
{
struct node *ptr;
if (head == NULL)
{
printf("UNDERFLOW\n");
}else if (head->next == head)
{
head = NULL;
free(head);
printf("Node Deleted\n");
}else
{
ptr = head;
while (ptr->next != head)
ptr = ptr->next;
ptr->next = head->next;
free(head);
head = ptr->next;
printf("Node Deleted\n");
}
}
執(zhí)行上面示例代碼,得到以下結(jié)果 -
1.Append List
2.Delete Node from beginning
3.Exit
4.Enter your choice?1
Enter the item
12
Node Inserted
1.Append List
2.Delete Node from beginning
3.Exit
4.Enter your choice?2
Node Deleted
¥ 我要打賞
糾錯/補充
收藏
加QQ群啦,易百教程官方技術(shù)學習群
注意:建議每個人選自己的技術(shù)方向加群,同一個QQ最多限加 3 個群。
總結(jié)
以上是生活随笔為你收集整理的Linux循环链表删除节点,删除循环单链表开头元素的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: linux如何取文件列名,Linux_根
- 下一篇: 笔记本nc10装linux,绝配:Ubu