分成两步走,简单遍历

  • val值前面一个循环
  • val值后面一个循环

c++实现

class Solution {
public:
    ListNode* insert(vector<int>& A, int val) {
        // write code here
        ListNode* head = new ListNode(0);
        ListNode* L = head;
        int i=0;
        while(A[i] < val && i<A.size()){
            L->next = new ListNode(A[i]);
            L = L->next;
            i++;
        }
        L->next = new ListNode(val);
        L = L->next;
        while(i<A.size()){
            L->next = new ListNode(A[i]);
            L = L->next;
            i++;
        }
        return head->next;
    }
};