向单链表中插入一个新结点

本文详细解析了在单链表中插入新节点的时间复杂度问题,包括在给定值后的插入操作和已知节点后的插入操作,阐述了不同情况下的时间复杂度差异及其原因。

1. 对于一个具有N个结点的单链表,在给定值为x的结点后插入一个新结点的时间复杂度为()。

A.O(1)

B.O(N/2)

C.O(N)

D.O(N^2)

正确答案:C

2. 对于一个具有N个结点的单链表,在已知的结点*p后插入一个新结点的时间复杂度为(O(1))。

解析:查找给定值为 x 的结点需要遍历整个单链表,因此在其后插入一个新结点的时间复杂度为O(n);而在已知结点*p的条件下,只需在结点*p后插入新结点即可,无需遍历链表,因此在其后插入一个新结点的时间复杂度为O(1)。

对于第一个问题,实现正序或逆序生成单链表的代码示例如下: // 定义单链表结构体 struct ListNode { int val; struct ListNode *next; }; // 正序生成单链表 struct ListNode* createList(int* nums, int numsSize) { struct ListNode* head = NULL; struct ListNode* tail = NULL; for (int i = 0; i < numsSize; i++) { struct ListNode* node = malloc(sizeof(struct ListNode)); node->val = nums[i]; node->next = NULL; if (head == NULL) { head = node; tail = node; } else { tail->next = node; tail = node; } } return head; } // 逆序生成单链表 struct ListNode* createListReverse(int* nums, int numsSize) { struct ListNode* head = NULL; for (int i = numsSize - 1; i >= 0; i--) { struct ListNode* node = malloc(sizeof(struct ListNode)); node->val = nums[i]; node->next = head; head = node; } return head; } 对于第二个问题,在单链表插入一个元素结点的代码示例如下: // 在单链表插入一个元素结点 void insertNode(struct ListNode* head, int index, int val) { struct ListNode* node = malloc(sizeof(struct ListNode)); node->val = val; struct ListNode* prev = NULL; struct ListNode* curr = head; for (int i = 0; i < index && curr != NULL; i++) { prev = curr; curr = curr->next; } if (prev == NULL) { node->next = head; head = node; } else { prev->next = node; node->next = curr; } } 对于第三个问题,在单链表中删除一个元素结点并回收该结点的代码示例如下: // 在单链表中删除一个元素结点并回收该结点 void deleteNode(struct ListNode* head, int index) { struct ListNode* prev = NULL; struct ListNode* curr = head; for (int i = 0; i < index && curr != NULL; i++) { prev = curr; curr = curr->next; } if (prev == NULL) { head = curr->next; } else { prev->next = curr->next; } free(curr); }
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值