输入为链表的表头
输出为需要打印的“新链表”的表头
/*** public class ListNode {* int val;* ListNode next = null;** ListNode(int val) {* this.val = val;* }* }**/import java.util.ArrayList;import java.util.Stack;public class Solution { public ArrayList<Integer> printListFromTailToHead(ListNode listNode) { ArrayList<Integer> result=new ArrayList(); if(listNode==null) return result; Stack<ListNode> stack=new Stack(); stack.push(listNode); while(listNode.next!=null) { stack.push(listNode.next); listNode=listNode.next; } while(!stack.isEmpty()) { ListNode node=stack.pop(); result.add(node.val); } return result; }}


这要弄清了,Java对象引用的关系理解起来就很容易了.下面就是实现的整个代码:
打印的结果为:
继续扩展下添加查找对应键值和按对应键值删除链结点的find和delete方法.
find方法:
这个方法与上面的displayLink方法类似.将current定义为first,通过不断的current.next.iData与键值作比较,如果相等便返回当前引用.
如果一直到最后Null也没找到就返回Null
delete方法:
这个方法需要两个变量.current:当前链结点的引用 privious:前一链结点的引用.这个方法也是通过循环查找如果找到了
.就用前一引用的next指向当前的next的引用就可以了.见图
最后代码:
执行结果:
原文:http://www.cnblogs.com/bb3q/p/5080993.html