问:实现接口,给定一个 LinkedList,能够反转节点顺序并返回新的 list 头。要求:只能使用基本数据类型
答:大约可回答
package com.xss.reverse; /** * 简单链表 */ public class SimpleNodeList { Object value; SimpleNodeList next; }
package com.xss.reverse; /** * 简单链表反转 */ public class SimpleNodeListTest { public static void main(String[] args) { SimpleNodeListTest test = new SimpleNodeListTest(); SimpleNodeList list = test.initSimpleNodeList(); SimpleNodeList node = test.reverse(list); test.printSimpleNodeList(node); } private SimpleNodeList reverse(SimpleNodeList list) { if (list == null || list.next == null) { return list; } SimpleNodeList node = null; while (list != null) { SimpleNodeList next = list.next; list.next = node; node = list; list = next; } return node; } private SimpleNodeList initSimpleNodeList() { SimpleNodeList list = new SimpleNodeList(); list.value = 0; SimpleNodeList node = list; for (int i = 0; i < 10; i++) { node.next = new SimpleNodeList(); node = node.next; node.value = i + 1; } return list; } private void printSimpleNodeList(SimpleNodeList node) { while (node != null) { System.out.print(node.value); node = node.next; if (node != null) { System.out.print("->"); } } } }