/* 访问链表中索引为 index 的节点 */ ListNode *access(ListNode *head, int index) { for (int i = 0; i < index; i++) { if (head == NULL) returnNULL; head = head->next; } return head; }
1 2 3 4 5 6 7 8 9
/* 访问链表中索引为 index 的节点 */ ListNode *access(ListNode *head, int index){ for (int i = 0; i < index; i++) { if (head == nullptr) returnnullptr; head = head->next; } return head; }
1 2 3 4 5 6 7
defaccess(head: ListNode, index: int) -> ListNode | None: """访问链表中索引为 index 的节点""" for _ inrange(index): ifnot head: returnNone head = head.next return head
2.5 查找节点
即遍历链表,找到所需值,时间复杂度和数组相同,都为$O(n)$。
1 2 3 4 5 6 7 8 9 10 11
/* 在链表中查找值为 target 的首个节点 */ intfind(ListNode *head, int target) { int index = 0; while (head) { if (head->val == target) return index; head = head->next; index++; } return-1; }
1 2 3 4 5 6 7 8 9 10 11
/* 在链表中查找值为 target 的首个节点 */ intfind(ListNode *head, int target){ int index = 0; while (head != nullptr) { if (head->val == target) return index; head = head->next; index++; } return-1; }
1 2 3 4 5 6 7 8 9
deffind(head: ListNode, target: int) -> int: """在链表中查找值为 target 的首个节点""" index = 0 while head: if head.val == target: return index head = head.next index += 1 return -1