题解 | 序列链表化
序列链表化
https://www.nowcoder.com/practice/a407f7e495084084b1e1f628dfd769fd?tpId=383&tqId=11211942&sourceUrl=%2Fexam%2Foj%3Fpage%3D1%26tab%3D%25E7%25AE%2597%25E6%25B3%2595%25E5%25AD%25A6%25E4%25B9%25A0%25E7%25AF%2587%26topicId%3D383
#include <stdlib.h>
/**
struct ListNode {int val;struct ListNode *next;};
*/
struct ListNode* vectorToListnode(int* arr, int arrLen) {// 如果数组为空或长度为0,返回空链表if (arr == NULL || arrLen == 0) {return NULL;}
// 创建头节点
struct ListNode* head = (struct ListNode*)malloc(sizeof(struct ListNode));
head->val = arr[0];
head->next = NULL;
struct ListNode* current = head;
// 遍历数组剩余元素,创建链表节点
for (int i = 1; i < arrLen; i++) {
struct ListNode* newNode = (struct ListNode*)malloc(sizeof(struct ListNode));
newNode->val = arr[i];
newNode->next = NULL;
current->next = newNode;
current = newNode;
}
return head;
}