查看: 560|回复: 0

[Java学习] Java实现单向链表反转

发表于 2018-4-15 08:00:01

本文实例为大家分享了Java实现单向链表反转的具体代码,供大家参考,具体内容如下

1、实现代码

  1. public class LinkedListTest {
  2. public static void main(String[] args) {
  3. Node A = new Node("A");
  4. Node B = new Node("B");
  5. Node C = new Node("C");
  6. Node D = new Node("D");
  7. Node E = new Node("E");
  8. Node F = new Node("F");
  9. A.next = B;
  10. B.next = C;
  11. C.next = D;
  12. D.next = E;
  13. E.next = F;
  14. print(A);
  15. LinkedListReversor reversor = LinkedListReversor.RECURSION;
  16. System.out.println(reversor.getStrategy() + ":");
  17. Node tmp = reversor.execute(A);
  18. print(tmp);
  19. reversor = LinkedListReversor.NO_RECURSION;
  20. System.out.println(reversor.getStrategy() + ":");
  21. print(reversor.execute(tmp));
  22. }
  23. private static void print(Node node) {
  24. while (node != null) {
  25. System.out.print(node.value);
  26. node = node.next;
  27. if (node != null) {
  28. System.out.print("->");
  29. } else {
  30. System.out.println();
  31. }
  32. }
  33. }
  34. }
  35. class Node {
  36. public String value;
  37. public Node next;
  38. public Node(String value) {
  39. this.value = value;
  40. }
  41. }
  42. enum LinkedListReversor {
  43. RECURSION("递归") {
  44. @Override
  45. public Node execute(Node node) {
  46. Node prev = null;
  47. if (node == null || node.next == null) {
  48. prev = node;
  49. } else {
  50. Node tmp = execute(node.next);
  51. node.next.next = node;
  52. node.next = null;
  53. prev = tmp;
  54. }
  55. return prev;
  56. }
  57. },
  58. NO_RECURSION("非递归") {
  59. @Override
  60. public Node execute(Node node) {
  61. Node prev = null;
  62. while (node != null) {
  63. Node tmp = node;
  64. node = node.next;
  65. tmp.next = prev;
  66. prev = tmp;
  67. }
  68. return prev;
  69. }
  70. };
  71. private String strategy;
  72. private LinkedListReversor(String strategy) {
  73. this.strategy = strategy;
  74. }
  75. public abstract Node execute(Node node);
  76. public String getStrategy() {
  77. return strategy;
  78. }
  79. }
复制代码

2、实现思路

递归:从尾部开始处理

非递归:从头部开始处理

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持程序员之家。



回复

使用道具 举报