C语言删除链表的第一个元素的代码
时间: 2024-05-05 21:15:37 浏览: 26
以下是C语言删除链表的第一个元素的代码:
```
#include <stdio.h>
#include <stdlib.h>
struct Node{
int data;
struct Node* next;
};
struct Node* deleteFirstNode(struct Node* head){
if(head == NULL){
printf("List is empty.\n");
return NULL;
}
struct Node* temp = head;
head = head->next;
free(temp);
return head;
}
int main(){
struct Node* head = NULL;
head = (struct Node*) malloc(sizeof(struct Node));
head->data = 1;
head->next = NULL;
struct Node* second = NULL;
second = (struct Node*) malloc(sizeof(struct Node));
second->data = 2;
second->next = NULL;
head->next = second;
struct Node* third = NULL;
third = (struct Node*) malloc(sizeof(struct Node));
third->data = 3;
third->next = NULL;
second->next = third;
printf("List before deletion:\n");
struct Node* current = head;
while(current != NULL){
printf("%d ", current->data);
current = current->next;
}
printf("\n");
head = deleteFirstNode(head);
printf("List after deletion:\n");
current = head;
while(current != NULL){
printf("%d ", current->data);
current = current->next;
}
printf("\n");
return 0;
}
```
这个程序定义了一个`Node`结构体,用于表示链表的节点。`deleteFirstNode`函数用于删除链表的第一个元素。如果链表为空,它会打印一条错误消息并返回`NULL`。否则,它会将链表的头指针指向第二个节点,并释放第一个节点的内存。该函数返回更新后的头指针。
在`main`函数中,我们创建了一个包含3个节点的链表,并打升序打印了它。然后我们调用`deleteFirstNode`函数来删除第一个节点,再次打印链表。
相关推荐
![cpp](https://img-home.csdnimg.cn/images/20210720083646.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)