【PTA数据结构 | C语言版】在单链表 list 的第 i 个位置上插入元素 x

本专栏持续输出数据结构题目集,欢迎订阅。

文章目录

    • 题目
    • 代码

题目

请编写程序,将 n 个整数插入初始为空的单链表,第 i 个整数插入在第 i 个位置上。注意:i 代表位序,从 1 开始。插入结束后,输出链表长度,并顺序输出链表中的每个结点的数值。最后,尝试将最后一个整数插入到链表的第 0 个、第 n+2 个位置上,以测试错误信息的输出。

输入格式:
输入首先在第一行给出正整数 n(≤20);随后一行给出 n 个 int 范围内的整数,数字间以空格分隔。

输出格式:
按照题面描述的要求,首先在第 1 行输出链表信息,格式为:

表长: x1 x2 ... xn

注意数字间有 1 个空格分隔,行首尾无多余空格。
在第 2、3 行分别输出将最后一个整数插入到链表的第 0 个、第 n+2 个位置上的信息 —— 当插入位置不合法时,应输出 错误:插入位置不合法。

输入样例:
5
1 2 3 4 5

输出样例:
5: 1 2 3 4 5
错误:插入位置不合法。
错误:插入位置不合法。

代码

#include 
#include 

// 链表节点结构定义
typedef struct Node {
    int data;           // 节点存储的数据
    struct Node* next;  // 指向下一个节点的指针
} Node;

// 创建新节点
Node* createNode(int data) {
    Node* newNode = (Node*)malloc(sizeof(Node));
    newNode->data = data;
    newNode->next = NULL;
    return newNode;
}

// 在指定位置插入节点(位序从1开始)
Node* insertNode(Node* head, int position, int data) {
    if (position < 1) return head;  // 位置非法,直接返回
    
    Node* newNode = createNode(data);
    
    // 插入到表头的情况
    if (position == 1) {
        newNode->next = head;
        return newNode;
    }
    
    // 寻找插入位置的前一个节点
    Node* current = head;
    for (int i = 1; i < position - 1 && current != NULL; i++)
        current = current->next;
    
    // 位置超出链表长度,丢弃新节点
    if (current == NULL) {
        free(newNode);
        return head;
    }
    
    // 插入新节点
    newNode->next = current->next;
    current->next = newNode;
    return head;
}

// 计算链表长度
int getLength(Node* head) {
    int length = 0;
    Node* current = head;
    while (current != NULL) {
        length++;
        current = current->next;
    }
    return length;
}

// 按格式输出链表
void printList(Node* head) {
    Node* current = head;
    int first = 1;  // 用于控制空格输出
    while (current != NULL) {
        if (!first) printf(" ");
        printf("%d", current->data);
        first = 0;
        current = current->next;
    }
    printf("\n");
}

int main() {
    int n;
    scanf("%d", &n);  // 读取整数个数
    
    Node* head = NULL;
    int value;
    
    // 按位序插入n个整数
    for (int i = 1; i <= n; i++) {
        scanf("%d", &value);
        head = insertNode(head, i, value);
    }
    
    // 输出链表信息
    printf("%d: ", getLength(head));
    printList(head);
    
    // 获取最后一个整数
    int lastValue = 0;
    Node* current = head;
    if (current != NULL) {
        while (current->next != NULL)
            current = current->next;
        lastValue = current->data;
    }
    
    insertNode(head, 0, lastValue);
    printf("错误:插入位置不合法。\n");
    
    insertNode(head, n + 2, lastValue);
    printf("错误:插入位置不合法。\n");
    
    return 0;
}    

你可能感兴趣的:(【PTA数据结构 | C语言版】在单链表 list 的第 i 个位置上插入元素 x)