6. Let $a_{1}, a_{2}, \cdots, a_{k}$ be a finite sequence of positive integers not exceeding $n$, where each term is different from its two adjacent terms and there do not exist any four indices $p<q<r<s$, such that $a_{p}=a_{s} \neq a_{q}=a_{r}$. Find the maximum value of the number of terms $k$.

Translate the above text into English, please keep the original text's line breaks and format, and output the translation result directly.
$$
\begin{array}{l}
n, n, n-1, n-1, \cdots, 2,2,1,1, \\
2,2, \cdots, n-1, n-1, n, n
\end{array}
$$

To meet the requirements, it has $k=4n-2$ terms. We need to prove that the number of terms is no less than $4n-2$. Any three consecutive terms cannot be the same number. Moreover, if a term can be adjacent to (or the first term, the last term's adjacent term) a term with a different number, then when adding a term with the same number next to it, the new sequence still meets the requirements, and the number of terms increases. We only need to consider the number of terms in any sequence where any two consecutive terms are different, as the latter's number of terms can be doubled to be the former's number of terms. Below, we use induction to prove: If the sequence $a_{1}, a_{2}, \cdots, a_{k}$ has any two consecutive terms with different values and $a_{1} \in \{1,2, \cdots, n\}, j=1, \cdots, h$, and there do not exist four indices $p1$, then the following holds:
$$
A=\left\{a_{1}, a_{2}, \cdots, a_{v}\right\}, B=\left\{a_{v+1},\right.
$$
‥ $\left.a_{v-1}\right\}$ do not have any common terms. Therefore, if we denote the number of different values in the terms of $A$ as $s$ and the number of different values in the terms of $B$ as $t$, then $s+t \leqslant m+1$. This way, from $A$ and $B$, two sequences that meet the requirements can be formed, and $s \leqslant m, t \leqslant m$. Thus, by the induction hypothesis, the number of terms in each sequence is $v \leqslant 2s-1$, $k-v-1 \leqslant 2t-1$. Therefore, we have
$$
\begin{array}{l}
k \leqslant 2t+v \leqslant 2t+2s-1=2(t+s)-1 \\
\leqslant 2(m+1)-1 .
\end{array}
$$

This completes the induction proof.