C语言单链表操作:创建、删除、插入、查找
#include <stdio.h> #include <stdlib.h>
// 定义链表结点 typedef struct Node { int data; struct Node* next; } Node;
// 创建链表 Node* createLinkedList() { Node* head = NULL; Node* tail = NULL;
int num;
scanf("%d", &num);
while (num != 0) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = num;
newNode->next = NULL;
if (head == NULL) {
head = newNode;
tail = newNode;
} else {
tail->next = newNode;
tail = newNode;
}
scanf("%d", &num);
}
return head;
}
// 输出链表所有元素 void printLinkedList(Node* head) { Node* current = head;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
printf("\n");
}
// 删除第一个元素 Node* deleteFirstNode(Node* head) { if (head == NULL) { return NULL; }
Node* temp = head;
head = head->next;
free(temp);
return head;
}
// 计算链表长度 int getLinkedListLength(Node* head) { int length = 0; Node* current = head;
while (current != NULL) {
length++;
current = current->next;
}
return length;
}
// 在第二个元素处插入新元素 Node* insertElement(Node* head, int element) { Node* newNode = (Node*)malloc(sizeof(Node)); newNode->data = element;
if (head == NULL) {
newNode->next = NULL;
return newNode;
}
Node* current = head;
int count = 1;
while (current->next != NULL && count < 2) {
current = current->next;
count++;
}
newNode->next = current->next;
current->next = newNode;
return head;
}
// 查找元素所在位置 int findElement(Node* head, int element) { int position = 1; Node* current = head;
while (current != NULL) {
if (current->data == element) {
return position;
}
current = current->next;
position++;
}
return -1;
}
int main() { // 创建链表 Node* A = createLinkedList();
// 输出所有元素
printLinkedList(A);
// 删除第一个元素
A = deleteFirstNode(A);
// 输出删除后的元素
printLinkedList(A);
// 输出链表长度
int length = getLinkedListLength(A);
printf("%d\n", length);
// 在第二个元素处插入新元素
A = insertElement(A, 100);
// 输出第一个元素100所在位置
int position = findElement(A, 100);
printf("%d\n", position);
return 0;
}
原文地址: https://www.cveoy.top/t/topic/o8Dw 著作权归作者所有。请勿转载和采集!