编程题首尾互换怎么写的

时间:2025-03-04 07:11:27 明星趣事

首尾互换的实现方法取决于所使用的编程语言和数据结构。下面我将提供几种不同编程语言中实现首尾互换的方法。

C++:

```cpp

include

include

include

int main() {

std::vector vec = {1, 2, 3, 4, 5, 6, 7, 8, 9};

std::reverse(vec.begin(), vec.end());

for (int i : vec) {

std::cout<< i << " ";

}

std::cout << std::endl;

return 0;

}

```

Java:

```java

public class Main {

public static void main(String[] args) {

int[] score = {1, 2, 3, 4, 5, 6, 7, 8, 9};

for (int i = 0; i < score.length / 2; i++) {

int temp = score[i];

score[i] = score[score.length - 1 - i];

score[score.length - 1 - i] = temp;

}

for (int i = 0; i < score.length; i++) {

System.out.print(score[i] + " ");

}

}

}

```

Python:

```python

def swap_elements(arr):

arr[:] = arr[::-1]

return arr

使用示例

arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]

print(swap_elements(arr))

```

JavaScript:

```javascript

function swapElements(arr) {

arr.reverse();

return arr;

}

// 使用示例

let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];

console.log(swapElements(arr));

```

C:

```csharp

using System;

using System.Linq;

class Program {

static void Main() {

int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9};

arr = arr.Reverse().ToArray();

foreach (int i in arr) {

Console.Write(i + " ");

}

}

}

```

以上是几种不同编程语言中实现首尾互换的方法。你可以根据自己的编程语言选择合适的方法来实现。如果你使用的是其他编程语言,可以参考上述示例代码进行相应的修改。