/* 带有哨兵的链表。哨兵所在的位置是真正列表开始前的一位。记住这一点,即可轻松理解哨兵含义,并编写addFirst和addLast方法。*/
// first是否为空影响某些情况的判断,既然这样,找一个哨兵,指向first。就可解决这一问题。这个思路很好。
public class SLList_1{
public static class IntNode{
public int item;
public IntNode next;
public IntNode(int i, IntNode n){
item = i;
next = n;
}
}
public IntNode sentry;
public int size;
public SLList_1(){
sentry = new IntNode(1, null);
size = 0;
}
public SLList_1(int x){
sentry = new IntNode(1, null);
sentry.next = new IntNode(x, null);
size = 1;
}
public void addFirst(int x){
sentry.next = new IntNode(x, sentry.next);
size += 1;
}
public void addLast(int x){
// 不论此时真正的链表是否为空,都不影响。
IntNode p = sentry;
if(p.next != null){
p = p.next;
}
p.next = new IntNode(x, null);
size += 1;
}
public int getSize() {
return size;
}
public static void main(String[] args) {
SLList_1 L = new SLList_1();
L.addFirst(5);
L.addLast(10);
System.out.print(L.getSize());
}
}