首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

C 語言順序鏈表插入節點保持有序:遍歷找位置插入

     編輯:程式設計綜合問答

順序鏈表(單向鏈表)按值遞增有序,插入新值 `x` 維持有序。

演算法步驟

  1. 建立新節點 `p = (Node*)malloc(sizeof(Node)); p->data = x;`
  2. 若空表或 `x <= head->data`:`p->next = head; head = p;`
  3. 否則遍歷:`Node *cur = head; while (cur->next && cur->next->data < x) cur = cur->next;`
  4. 插入:`p->next = cur->next; cur->next = p;`

完整代碼

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)。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved