【Java】实现一个递归和非递归的reverse,它们能把一个表翻转过来。

时间:2021-07-09 13:21:18

【Java】实现一个递归和非递归的reverse,它们能把一个表翻转过来。操作中不要建立新的表项,只用已有的项。(表使用LinkedList<Integer>)


1.代码实现


package devin.wu.readbook;

import java.util.LinkedList;

public class ReverseTools
{

public static void reverse(LinkedList<Integer> list, int i)
{
int size = list.size();
if (i < size / 2)
{
swapItemByIndex(list, i, size - 1 - i);

reverse(list, i + 1);
}
}

public static void reverse(LinkedList<Integer> list)
{
int size = list.size();
for (int i = 0; i < size / 2; i++)
{
swapItemByIndex(list, i, size - 1 - i);
}

}

private static void swapItemByIndex(LinkedList<Integer> list, int i, int j)
{
list.set(i, list.get(i) + list.get(j));
list.set(j, list.get(i) - list.get(j));
list.set(i, list.get(i) - list.get(j));
}

public static void main(String[] args)
{
LinkedList<Integer> list = new LinkedList<Integer>();
list.add(1);
list.add(2);
list.add(3);
list.add(4);
list.add(5);

System.out.println("-------------To print the initial linked list.--------------------");
printLinkedList(list);

System.out.println("-------------After reversing by recursion.--------------------");
reverse(list);
printLinkedList(list);

System.out.println("-------------After reversing by iteration.--------------------");
reverse(list, 0);
printLinkedList(list);

}

private static void printLinkedList(LinkedList<Integer> list)
{
for (Integer element : list)
{
System.out.println(element);
}
}

}

2.运行效果


-------------To print the initial linked list.--------------------
1
2
3
4
5
-------------After reversing by recursion.--------------------
5
4
3
2
1
-------------After reversing by iteration.--------------------
1
2
3
4
5