翻转单链表

来源:互联网 发布:英迈零售软件 编辑:程序博客网 时间:2024/05/16 00:50

增加一种递归法翻转单链表的方法:

package cn.lktbl;import com.alibaba.fastjson.JSON;public class ReversLinkTable {public static void main(String[] args) {Node n1 = new Node(1, new Node(2, new Node(3, new Node(4, new Node(5, new Node(6, null))))));System.out.println(JSON.toJSON(n1));System.out.println(JSON.toJSON(reverse(n1)));}private static Node reverse(Node node) {if ((node == null) || (node.next == null)) {return node;}Node head = reverse(node.next);node.next.next = node;node.next = null;return head;}static class Node {public int value;public Node next;public Node(int value, Node next) {this.next = next;this.value = value;}}}

输出结果:


原创粉丝点击