CS61B学习日记1
总结:
1.今天学习使用Java复习最简单链表->具有头结点的链表(或者头结点叫哨兵)->双向链表。
以及对哨兵的优化更改方案:
1).将哨兵作为头尾节点
2)将列表实现为循环列表
2.今天完成了lab2,顺便也熟悉了一下如何autograde
2.1-2.3List文件
package com.cs61b.initclass;
import edu.princeton.cs.algs4.In;
/**
* Notice:this code is iterative from IntList -> SLList -> DLList
* simple List-> indirect call List -> doubly Linked List
* (And DLList program code inner SLList code)
**/
public class SLList {
//nested Classes
public class IntNode {
public IntNode pre;
public int item;
public IntNode next;
public IntNode(int i, IntNode n) {
item = i;
next = n;
}
}
//设置的哨兵节点:sentinel,也就我们所说的头结点
private IntNode sentinel;
private IntNode last;
private int size;
public SLList(int x){
sentinel = new IntNode(0,new IntNode(x,null));
sentinel.next.pre = sentinel;
//init LastNode and newNode modified
last = new IntNode(0,null);
last.pre = sentinel.next;
last.pre.next = last;
++size;//使用哨兵节点的value为List的Size
}
//recursive retail insert
public void addItem(int x){
//first modify oldNode pre-pointer
sentinel.next.pre = new IntNode(x,sentinel.next);
//second newNode pre-pointer to sentinel
sentinel.next.pre.pre = sentinel;
++size;
}
//recursive sentinel item
public int getFirst(){
return sentinel.next.item;
}
// //iterative addLast
// public void addLast(int x){
// IntNode p = sentinel;
// while(p.next != null){
// p = p.next;
// }
// p.next = new IntNode(x,null);
// //modify LastNode store address
// last = sentinel.next;
// ++sentinel.item;
// }
public void addLast(int x){
//important step:Must be modifying newLast preNode
//additionally:move Last.Pre Point to newLastNode
//retail insert method
this.last.pre.next = new IntNode(x,null);
//new retailNode-pre point LastOldPre
this.last.pre.next.pre = this.last.pre;
this.last.pre = this.last.pre.next;
this.last.pre.next = this.last;
++size;
}
public boolean removeLast(){
return removeLastInstance();
}
private boolean removeLastInstance(){
if(this.size == 0){
return false;
}
IntNode temp = this.last.pre;
this.last.pre = this.last.pre.pre;
this.last.pre.next = this.last;
temp = null;
--size;
return true;
}
//静态私有长度的计算
private static int size(IntNode p){
if(p.next == null){
return 1;
}
return 1+size(p.next);
}
public int getSize() {
return this.size;
}
public int getLast() {
return this.last.pre.item;
}
}
Lab2总结
学会使用debug进调试程序。
tips:其中隐藏bug关于位运算
将普通数据结构类型改为泛型接受数据
在调用类后面加上
class DLList<T>{
...
class InitNode{
public InitNode pre;
public T item;
public InitNode next;
public IntNode(T i, IntNode n) {
item = i;
next = n;
}
}
...
}
在进行实例化调用时,如下所示:
DLList<Integer> L = new DLList<>(15)
只需要在空<>
中指定元素值类型。
tips:在基本类型上实例化泛型,请使用 Integer 、 Double 、 Character 、 Boolean 、 Long 、 Byte 或 Float 。
本文作者:duuuuu17
本文链接:https://www.cnblogs.com/duuuuu17/p/17681206.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步