HJ48 从单向链表中删除指定值的节点

题目:

HJ48 从单向链表中删除指定值的节点

题解:

  1. 按照题意构造链表
  2. 遍历链表删除指定字符
    public String removeFromLinked(String string) {
        LinkedList linkedList = new LinkedList<>();
        String[] strings = string.split(" ");
        String firstNode = strings[1];

        linkedList.addFirst(firstNode);
        for (int i = 2; i < strings.length - 1 ;) {
            String value1 = strings[i];
            String value2 = strings[i+1];
            instLinked(linkedList, value1, value2);
            i = i + 2;
        }

        String deleteValue = strings[strings.length - 1];
        linkedList.removeIf(integer -> integer.equals(deleteValue));

        return String.join(" ", linkedList);
    }

    private void instLinked(LinkedList linkedList, String value1, String value2) {
        int i;
        for (i = 0; i < linkedList.size(); i++) {
            if (linkedList.get(i).equals(value2)) {
                break;
            }
        }

        linkedList.add(i+1, value1);
    }

时间复杂度:O(n)

你可能感兴趣的:(链表,华为)