一种数据结构:SLList

In the last session, we discovered a kind of data structure whose name is IntList. Below is its code:

public class IntList{
    public int first;
    pubic IntList rest;
    
    public IntList(int f, IntList r){
        first =f;
        rest = r;
    }
}

It is called the 'naked recursive implementation'. However, in Java, it is a little bit awkward. So the topic of this article is how to improve this.

To begin with, I need to change the names of IntList

public class IntNode{
    public int item;
    public IntNode next;
    
    public IntNode(int i, IntNode n){
        item = i;
        next = n;
    }
}

As we all know, this is called a 'linked list'. Next, we need to make some improvement. It is because every time i want to instantiate the IntNode, I have to write a code like this: IntNode L = new IntNode (3, null);

Apparently, it is not terse.

So,we need to create another class SLList to make it operate easier.

public class SLList{
    public IntNode first;
    
    public SLList (int x) {
        first = new IntNode (x, null);
    }
       
    public class IntNode{
            public int item;
            public IntNode next;
    
            public IntNode(int i, IntNode n){
                item = i;
                next = n;
            }
    } 
}                               

Thus, every time we want to create a SLList, we just need to use this code: SLList L = new SLList (10);

Now let's add the two methods: addFirst and getFirst:

public class SLList{
   .......
    public void addFirst(int x){
        first = new IntNode (first, null);
    
    }
    public int getFirst(){
        return first.item;
    }
}               

Then we can add another two methods: addLast and Size:

public class SLList{
   .......
    public void addLast(int x){
        if (first.next == null){
            first.next = IntNode(x,null);
        }
        else{
            addLast(first.next.next);
        }
}                       
public class SLList{
   .......
    public int size(){
        IntNode p = first;
        int size = 1;
        while (p.next != null) {
            size+=1;
            p = p.next
        }
    return size;
}                   

By contrast, I implement the addLast method resursively and the size method itratively, but this SLList class is still far from perfect.

 

posted @ 2021-01-26 20:40  M1stF0rest  阅读(158)  评论(0)    收藏  举报