我做了一个SListClass
代表单链表类和一个节点类SListNode
。我的removeLast
方法有问题。当我打印出节点列表时,第一项仍然存在。我不明白为什么
public class SListClass {
private SListNode head;
private double size;
SListClass(){
head = null;
size = 0;
}
SListClass(SListNode node){
head = node;
}
public void insertFront(int item){
head = new SListNode(item, head);
size++;
}
public void addLast(SListNode head, int value){
SListNode first = head;
while(first.next != null){
first = first.next;
}
first.next = new SListNode(value, null);
size++;
}
public void removeFirst(SListNode head){
head = head.next;
}
/*public String toString(){
return String.format(head + "");
}
*/
public String print(){
String result = head.item + " ";
if(head.next != null){
result += head.next.print();
}
return result;
}
public static void main(String[] args) {
SListNode list = new SListNode(21, new SListNode(5, new SListNode(19, null)));
SListClass x = new SListClass(list);
x.insertFront(33);
x.insertFront(100);
x.addLast(list, 123);
x.addLast(list, 9999);
x.removeFirst(list);
System.out.println(x.print());
}
}
output: 100 33 21 5 19 123 9999
SListNode
班级:
public class SListNode {
protected int item;
protected SListNode next;
public SListNode(int item, SListNode next){
this.item = item;
this.next = next;
}
public SListNode(int item){
this(item, null);
}
public int getItem() {
return item;
}
public void setItem(int item) {
this.item = item;
}
public SListNode getNext() {
return next;
}
public void setNext(SListNode next) {
this.next = next;
}
}