单链表反转

Posted sakura1027

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了单链表反转相关的知识,希望对你有一定的参考价值。

 1 package jzoffer;
 2 
 3 /**
 4  * Created by sakura on 2018/3/18.
 5  */
 6 class Node {
 7     String val;
 8     Node next;
 9     Node(String val) {
10         this.val = val;
11     }
12 }
13 public class ReverseList {
14     public static void main(String[] args) {
15         Node A = new Node("A");
16         Node B = new Node("B");
17         Node C = new Node("C");
18         Node D = new Node("D");
19         Node E = new Node("E");
20         Node F = new Node("F");
21         A.next = B;
22         B.next = C;
23         C.next = D;
24         D.next = E;
25         E.next = F;
26         System.out.print("初始化链表:");
27         print(A);
28         System.out.print("循环翻转后:");
29         Node head=ReverseListByLoop(A);
30         print(head);
31         System.out.print("递归翻转后:");
32         print(ReverseListByRecursion(head));
33     }
34 
35     private static void print(Node node) {
36         while (node != null) {
37             System.out.print(node.val);
38             node = node.next;
39             if (node != null)
40                 System.out.print("->");
41             else
42                 System.out.println();
43         }
44     }
45 
46     public static Node ReverseListByLoop(Node head) {
47         Node pre = null;
48         Node next = null;
49         while(head!=null){
50             next = head.next;
51             head.next = pre;
52             pre = head;
53             head = next;
54         }
55         return pre;
56     }
57 
58     public static Node ReverseListByRecursion(Node head){
59         if(head==null||head.next ==null)
60             return head;
61         Node prev = ReverseListByRecursion(head.next);
62         head.next.next = head;
63         head.next = null;
64         return prev;
65     }
66 
67 }
68 /*
69 初始化链表:A->B->C->D->E->F
70 循环翻转后:F->E->D->C->B->A
71 递归翻转后:A->B->C->D->E->F
72  */

 

以上是关于单链表反转的主要内容,如果未能解决你的问题,请参考以下文章

手撕代码之反转单链表

反转单链表

单链表反转

小代码 单链表之反转 然后交错重连+稀疏矩阵

递归-反转单链表 -图解

看一遍就理解,图解单链表反转