活跃农民
- 积分
- 823
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2014-11-2
- 最后登录
- 1970-1-1
|
先贴图:
题目意思好绕,constant time就好了,后面说了一堆record, representation之类的, 感觉不如直接说keep track of the tail。。。
要改的三个是:加一个instance variable (tail),insertFront(), insertEnd();
人认为有两种实现带tail的linkedlist的思路:
1. head和tail指向的都是首末的有意义的node:
优点:代码简洁,节约了两个node;
缺点:insertFront()和insertEnd()里都要把tail==0拎出来单独讨论;
2. head和tail分别指的首末的无意义的(不存item)node,专门作首尾节点:
优点:是课堂上讲的标准linkedlist结构
缺点:代码稍微复杂一点,又因为是单向linkedlist,没有prev,所以尾node的next要往回指,容易弄错。。(事实上1中的node本身也是往回指的。。)
贴一下1的代码:- public void insertFront(Object obj) {
- head = new SListNode(obj, head);
- if (tail == null){
- tail = head;
- }
- size++;
- }
- public void insertEnd(Object obj) {
- if (tail==null){
- insertFront(obj);
- } else {
- tail.next = new SListNode(obj, null);
- tail = tail.next;
- size++;
- }
- }
复制代码 2的代码就是把一些head和tail改成head.next和tail.next,然后不用分情况讨论了,略了;
|
|