本篇内容主要讲解“Java反转链表怎么测试”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“Java反转链表怎么测试”吧!
便于增删数据,不便于寻址
在内存中属于跳转结构
单链表: 值,一条next指针
双链表:值,一条last指针,一条next指针
public static class Node { public int value; public Node next; public Node(int value) { this.value = value; } @Override public String toString() { ArrayList<Integer> nums = new ArrayList<>(); Node node = this; while (node != null) { nums.add(node.value); node = node.next; } return nums.toString(); } }
public static Node reverseLinkedList(Node head) { Node next = null; Node pre = null; while (head != null) { next = head.next; head.next = pre; pre = head; head = next; } return pre; }
public static void main(String[] args) { Node node = new Node(1); node.next = new Node(2); node.next.next = new Node(3); node = reverseLinkedList(node); System.out.println(node); }
输出结果如下:
[3, 2, 1]
public static class DoubleList { public int value; public DoubleList next; public DoubleList last; public DoubleList(int value) { this.value = value; } @Override public String toString() { ArrayList<Integer> nums = new ArrayList<>(); DoubleList node = this; while (node != null) { nums.add(node.value); node = node.next; } return nums.toString(); } }
public static DoubleList reverseDoubleList(DoubleList head) { DoubleList next; DoubleList pre = null; while (head != null) { next = head.next; head.next = pre; // 注意和单项链表不一样的地方只有这一行,其他都基本一样 head.last = next; pre = head; head = next; } return pre; }
public static void main(String[] args) { DoubleList node1 = new DoubleList(1); node1.next = new DoubleList(2); node1.next.last = node1; node1.next.next = new DoubleList(3); node1.next.next.last = node1.next; System.out.println("reverseDoubleList(node1) = " + reverseDoubleList(node1)); }
输出结果如下:
reverseDoubleList(node1) = [3, 2, 1]
到此,相信大家对“Java反转链表怎么测试”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。