解釋連結串列中元素的刪除
連結串列使用動態記憶體分配,即它們會相應增長和收縮。它們被定義為節點的集合。這裡,節點有兩個部分,即資料和連結。資料、連結和連結串列的表示如下 −

連結串列上的操作
C 語言中連結串列上的操作有三種類型,如下所示 −
- 插入
- 刪除
- 遍歷
刪除
考慮以下給出的示例 −
刪除節點 2

刪除節點 1

刪除節點 3

程式
以下是 C 語言中用於刪除連結串列中元素的程式 −
#include <stdio.h>
#include <stdlib.h>
struct Node{
int data;
struct Node *next;
};
void push(struct Node** head_ref, int new_data){
struct Node* new_node = (struct Node*) malloc(sizeof(struct Node));
new_node->data = new_data;
new_node->next = (*head_ref);
(*head_ref) = new_node;
}
void deleteNode(struct Node **head_ref, int position){
//if list is empty
if (*head_ref == NULL)
return;
struct Node* temp = *head_ref;
if (position == 0){
*head_ref = temp->next;
free(temp);
return;
}
for (int i=0; temp!=NULL && i<position-1; i++)
temp = temp->next;
if (temp == NULL || temp->next == NULL)
return;
struct Node *next = temp->next->next;
free(temp->next); // Free memory
temp->next = next;
}
void printList(struct Node *node){
while (node != NULL){
printf(" %d ", node->data);
node = node->next;
}
}
int main(){
struct Node* head = NULL;
push(&head, 7);
push(&head, 1);
push(&head, 3);
push(&head, 2);
push(&head, 8);
puts("Created List: ");
printList(head);
deleteNode(&head, 3);
puts("
List after Deletion at position 3: ");
printList(head);
return 0;
}輸出
當執行以上程式時,它會產生以下結果 −
Created List: 8 2 3 1 7 List after Deletion at position 3: 8 2 3 7
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP