#include <stdio.h> #include <stdlib.h>

// 定义单链表的结点结构 struct Node { int data; struct Node* next; };

// 创建单链表 struct Node* createLinkedList() { struct Node* head = NULL; // 头结点 struct Node* tail = NULL; // 尾结点

int num;
while (scanf("%d", &num) != EOF) {
    // 创建新结点
    struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
    newNode->data = num;
    newNode->next = NULL;

    if (head == NULL) {
        head = newNode;
        tail = newNode;
    } else {
        tail->next = newNode;
        tail = newNode;
    }
}

return head;

}

// 输出单链表的所有元素 void printLinkedList(struct Node* head) { struct Node* cur = head;

while (cur != NULL) {
    printf("%d ", cur->data);
    cur = cur->next;
}

printf("\n");

}

// 删除第一个元素 struct Node* deleteFirstNode(struct Node* head) { if (head == NULL) { return NULL; }

struct Node* newHead = head->next;
free(head);

return newHead;

}

// 计算单链表的长度 int getLinkedListLength(struct Node* head) { struct Node* cur = head; int count = 0;

while (cur != NULL) {
    count++;
    cur = cur->next;
}

return count;

}

// 在第二个元素处插入一个新的元素 struct Node* insertElement(struct Node* head, int element) { struct Node* newNode = (struct Node*)malloc(sizeof(struct Node)); newNode->data = element;

if (head == NULL) {
    newNode->next = NULL;
    return newNode;
}

struct Node* cur = head;
int count = 1;

while (count < 2 && cur->next != NULL) {
    cur = cur->next;
    count++;
}

newNode->next = cur->next;
cur->next = newNode;

return head;

}

// 查找第一个元素所在的位置 int findFirstElement(struct Node* head, int element) { struct Node* cur = head; int index = 0;

while (cur != NULL) {
    index++;
    if (cur->data == element) {
        return index;
    }
    cur = cur->next;
}

return -1;

}

int main() { struct Node* head = createLinkedList();

// 输出创建后的单链表
printLinkedList(head);

// 删除第一个元素
head = deleteFirstNode(head);
// 输出删除后的单链表
printLinkedList(head);

// 输出删除元素后的表的长度
int length = getLinkedListLength(head);
printf("%d\n", length);

// 在第二个元素处插入一个新的元素
head = insertElement(head, 100);
// 输出插入新元素后的单链表
printLinkedList(head);

// 输出第一个元素100所在位置
int position = findFirstElement(head, 100);
printf("%d\n", position);

return 0;

}

C语言单链表操作:创建、删除、插入、查找

原文地址: https://www.cveoy.top/t/topic/o8DB 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录