# include<stdio.h>
# include<stdlib.h>
typedef struct Node{//定义结构体
int data; // 数据域
struct Node* next; //指针域
}Node;
Node* init_List(int list[], int n){//链表初始化
if(n == 0) return NULL;
Node* head = NULL;
Node* tail = NULL;
for(int i = 0;i < n;i++){
Node* newnode = (Node*)malloc(sizeof(Node));
newnode->data = list[i];
newnode->next = NULL;
if(!head){
head = newnode;
tail = newnode;
}
else{
tail=tail->next = newnode;
}
}
return head;
}
void printlist(Node* head){ //打印链表
Node* temp = head;
while(temp){
printf("%d -> ",temp->data);
temp = temp->next;
}
printf("NULL\n");
}
Node* deletNode(Node* head, int key){//删除指定元素(所有重复值)
Node *delnode, *prenode;
if(head == NULL){
printf("链表为空");
}
delnode = head;
while(delnode){
if(delnode->data == key){
if(delnode == head){
head = head->next;
free(delnode);
delnode = head;
}
else{
prenode->next = delnode->next;
free(delnode);
delnode = prenode->next;
}
}
else{
prenode = delnode;
delnode = delnode->next;
}
}
return head;
}
int main(void)
{
int list[] = {3, 3, 5, 8, 3};
int n = sizeof(list)/sizeof(list[0]);
Node *head = init_List(list, n);
printlist(head);
head = deletNode(head,3);
printlist(head);
return 0;
}
带头节点的单向链表的节点删除
最新推荐文章于 2024-11-10 14:34:06 发布