MST

星途 面试题库

面试题:C语言循环链表的插入操作

请用C语言实现一个在循环链表指定位置插入新节点的函数。假设循环链表节点结构体定义为:struct Node { int data; struct Node *next; }; 函数接收循环链表头指针、要插入的数据以及指定位置作为参数。
27.8万 热度难度
编程语言C

知识考点

AI 面试

面试题答案

一键面试
#include <stdio.h>
#include <stdlib.h>

struct Node {
    int data;
    struct Node *next;
};

// 在循环链表指定位置插入新节点的函数
struct Node* insertAtPosition(struct Node *head, int data, int position) {
    struct Node *newNode = (struct Node*)malloc(sizeof(struct Node));
    newNode->data = data;
    if (position == 1) {
        struct Node *current = head;
        while (current->next != head) {
            current = current->next;
        }
        newNode->next = head;
        current->next = newNode;
        return newNode;
    }
    struct Node *current = head;
    int count = 1;
    while (current != NULL && count < position - 1) {
        current = current->next;
        count++;
    }
    if (current == NULL) {
        free(newNode);
        return head;
    }
    newNode->next = current->next;
    current->next = newNode;
    return head;
}