创建单链表:
首先,我们需要定义一个单链表节点的结构体,包含数据域和指针域。然后,我们可以使用malloc函数动态申请内存空间来创建节点,并按照需求逐个连接起来。
- #include <stdio.h>
- #include <stdlib.h>
- // 定义单链表节点的结构体
- typedef struct Node {
- int data; // 数据域
- struct Node* next; // 指针域
- } Node;
- // 创建单链表
- Node* createLinkedList(int arr[], int n) {
- Node* head = NULL; // 头节点初始化为空
- Node* tail = NULL; // 尾节点初始化为空
-
- for (int i = 0; i < n; i++) {
- // 创建新节点
- Node* newNode = (Node*)malloc(sizeof(Node));
- newNode->data = arr[i];
- newNode->next = NULL;
-
- // 第一个节点作为头节点
- if (head == NULL) {
- head = newNode;
- tail = newNode;
- }
- else {
- // 将节点连接到尾部
- tail->next = newNode;
- tail = tail->next;
- }
- }
-
- return head;
- }
复制代码
排序单链表:
排序单链表可以采用冒泡排序、选择排序等排序算法。这里以冒泡排序为例。
- // 排序单链表(冒泡排序)
- void sortLinkedList(Node* head) {
- Node* p;
- Node* q;
- int temp;
- for (p = head; p != NULL; p = p->next) {
- for (q = p->next; q != NULL; q = q->next) {
- if (p->data > q->data) {
- temp = p->data;
- p->data = q->data;
- q->data = temp;
- }
- }
- }
- }
复制代码
插入节点:
插入节点需要考虑在头部插入和中间插入两种情况。对于头部插入,只需要修改头节点指针即可;对于中间插入,需要找到插入位置的前一个节点,修改其指针域。
- // 在单链表head中的第position个位置插入节点
- void insertLinkedList(Node** head, int position, int data) {
- Node* newNode = (Node*)malloc(sizeof(Node));
- newNode->data = data;
- newNode->next = NULL;
- // 头部插入
- if (position == 0) {
- newNode->next = *head;
- *head = newNode;
- }
- else {
- // 找到插入位置的前一个节点
- Node* curr = *head;
- for (int i = 0; i < position - 1 && curr != NULL; i++) {
- curr = curr->next;
- }
- // 中间插入
- if (curr != NULL) {
- newNode->next = curr->next;
- curr->next = newNode;
- } else {
- printf("Position out of range.\n");
- free(newNode);
- }
- }
- }
复制代码
删除节点:
删除节点需要考虑删除头节点和中间节点两种情况。对于头节点,只需要修改头节点指针即可;对于中间节点,需要找到删除位置的前一个节点,修改其指针域。
- // 删除单链表head中的第position个节点
- void deleteLinkedList(Node** head, int position) {
- // 头节点为空
- if (*head == NULL) {
- printf("The linked list is empty.\n");
- return;
- }
- // 删除头节点
- if (position == 0) {
- Node* temp = *head;
- *head = (*head)->next;
- free(temp);
- }
- else {
- // 找到删除位置的前一个节点
- Node* curr = *head;
- for (int i = 0; i < position - 1 && curr->next != NULL; i++) {
- curr = curr->next;
- }
- // 中间删除
- if (curr->next != NULL) {
- Node* temp = curr->next;
- curr->next = curr->next->next;
- free(temp);
- } else {
- printf("Position out of range.\n");
- }
- }
- }
复制代码
以上是单链表的创建、排序、插入和删除的代码实现。你可以根据需要调用相应的函数来操作单链表。
以上回复来自 -- ChatGPT(FishC官方接口),如未能正确解答您的问题,请继续追问。