1. /**
    2. * @Description:反转单向链表和双向链表
    3. * @Author: lizhouwei
    4. * @CreateDate: 2018/4/6 11:07
    5. */
    6. public class Chapter2_4 {
    7. //反转单向链表
    8. public Node reverse(Node head){
    9. if(head ==null){
    10. return null;
    11. }
    12. Node pre = null;
    13. Node next=null;
    14. while (head!=null){
    15. next = head.next;
    16. head.next = pre;
    17. pre = head;
    18. head = next;
    19. }
    20. return pre;
    21. }
    22. //反转双向链表
    23. public DoubleNode reverseDNode(DoubleNode head){
    24. if(head ==null){
    25. return null;
    26. }
    27. DoubleNode pre = null;
    28. DoubleNode next=null;
    29. while (head!=null){
    30. next = head.next;
    31. head.next = pre;
    32. head.pre = next;
    33. pre = head;
    34. head = next;
    35. }
    36. return pre;
    37. }
    38. public void printLink(Node head) {
    39. System.out.println();
    40. while (head != null) {
    41. System.out.print(head.vlaue + " ");
    42. head = head.next;
    43. }
    44. }
    45. public void printDLink(DoubleNode head) {
    46. System.out.println();
    47. while (head != null) {
    48. System.out.print(head.vlaue + " ");
    49. head = head.next;
    50. }
    51. }
    52. //测试
    53. public static void main(String[] args) {
    54. Chapter2_4 chapter = new Chapter2_4();
    55. Link link1 = new Link();//单链表
    56. Link link2 = new Link();//双链表
    57. //构造链表
    58. for (int i = 10; i > 0; i--) {
    59. link1.add(i);
    60. link2.addDoubleNode(i);
    61. }
    62. chapter.printLink(link1.head);
    63. Node head = chapter.reverse(link1.head);
    64. chapter.printLink(head);
    65. chapter.printDLink(link2.dhead);
    66. DoubleNode dhead = chapter.reverseDNode(link2.dhead);
    67. chapter.printDLink(dhead);
    68. }
    69. }