给出C语言的基本链表操作
时间: 2024-05-22 08:13:23 浏览: 15
Sure, here are the basic linked list operations in C:
1. Creating a Linked List:
To create a linked list, we need to define a struct for the nodes and a function to insert new nodes.
struct Node {
int data;
struct Node* next;
};
struct Node* head = NULL;
2. Inserting a Node at the Beginning:
To insert a node at the beginning of the linked list, we need to create a new node, set its data and next pointer, and make it the new head.
void insertAtBeginning(int data) {
struct Node* newNode = (struct Node*) malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = head;
head = newNode;
}
3. Inserting a Node at the End:
To insert a node at the end of the linked list, we need to traverse the list to find the last node, create a new node, and make the last node's next pointer point to the new node.
void insertAtEnd(int data) {
struct Node* newNode = (struct Node*) malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = NULL;
if (head == NULL) {
head = newNode;
return;
}
struct Node* last = head;
while (last->next != NULL) {
last = last->next;
}
last->next = newNode;
}
4. Deleting a Node:
To delete a node from the linked list, we need to find the node to be deleted and make its previous node's next pointer point to its next node.
void deleteNode(int key) {
struct Node* temp = head, *prev;
if (temp != NULL && temp->data == key) {
head = temp->next;
free(temp);
return;
}
while (temp != NULL && temp->data != key) {
prev = temp;
temp = temp->next;
}
if (temp == NULL) {
return;
}
prev->next = temp->next;
free(temp);
}
I hope that helps! Let me know if you have any more questions.
相关推荐
![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)