码迷,mamicode.com
首页 > 其他好文 > 详细

单链表反转

时间:2018-03-18 15:04:20      阅读:153      评论:0      收藏:0      [点我收藏+]

标签:ever   pos   oop   []   ext   ted   created   ==   color   

 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  */

 

单链表反转

标签:ever   pos   oop   []   ext   ted   created   ==   color   

原文地址:https://www.cnblogs.com/sakura1027/p/8595235.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!