#include<stdio.h>
#include<stdlib.h>
// 定义链表节点
struct Node {
int data;
struct Node* next;
};
// 函数用于创建新的节点
struct Node* createNewNode(int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = NULL;
return newNode;
}
// 函数用于将新节点添加到链表的末尾
struct Node* addNode(struct Node* head, int data) {
struct Node* newNode = createNewNode(data);
if (head == NULL) {
head = newNode;
} else {
struct Node* temp = head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newNode;
}
return head;
}
// 函数用于在链表中搜索给定的元素
struct Node* search(struct Node* head, int key) {
struct Node* temp = head;
while (temp != NULL) {
if (temp->data == key) {
return temp;
}
temp = temp->next;
}
return NULL;
}
int main() {
struct Node* head = NULL;
// 添加节点到链表
head = addNode(head, 10);
head = addNode(head, 20);
head = addNode(head, 30);
head = addNode(head, 40);
// 在链表中搜索元素
int key = 30;
struct Node* found = search(head, key);
if (found != NULL) {
printf("Element %d found in the list\n", key);
} else {
printf("Element %d not found in the list\n", key);
}
return 0;
}