PART I:
没什么好说的。。第一个前向后向添加都行,第二个前面加一个后面加一个就行了
代码及结果:
public static void main (String[] args) { SList l1=new SList(); l1.insertFront(new Integer(12)); l1.insertFront(new Integer(9)); l1.insertFront(new Integer(6)); System.out.println("insert step1: "+ l1.toString()); // Fill in your solution for Part I here. l1.insertFront(new Integer(3)); l1.insertEnd(new Integer(15)); System.out.println("insert step2: "+ l1.toString());
PART II:
根据题目要求,再多加上一个tail指向链表末端,通过tail实现后向添加。注意第一次初始化的时候head, tail为null的情况
几处更改:类的定义:
public class SList { private SListNode head; private SListNode tail; private int size; /** * SList() constructs an empty list. **/ public SList() { size = 0; head = null; tail = null; }
前向和后向插入:
public void insertFront(Object obj) { head = new SListNode(obj, head); if (tail==null) { tail=head; } size++; } public void insertEnd(Object obj) { if (tail==null) { tail=new SListNode(obj,tail); head=tail; } else { tail.next=new SListNode(obj); tail=tail.next; } size++; }
结果: