順序鏈表(單向鏈表)按值遞增有序,插入新值 `x` 維持有序。
typedef struct Node { int data; struct Node *next; } Node;
Node* insertSorted(Node *head, int x) {
Node *p = (Node*)malloc(sizeof(Node));
p->data = x; p->next = NULL;
if (!head || x <= head->data) { p->next = head; return p; }
Node *cur = head;
while (cur->next && cur->next->data < x) cur = cur->next;
p->next = cur->next;
cur->next = p;
return head;
}
時間複雜度 O(n),空間 O(1)。