数据结构-CS61B学习日记

发布时间 2023-09-05 23:46:26作者: duuuuu17

总结:

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关于位运算