Add a method to the SLList class that inserts a new element at the given position. If the position is past the end of the list, insert the new node at the end of the list. For example, if the SLList is 5 –> 6 –> 2, insert(10, 1) should result in 5 –> 10 –> 6 –> 2.
public void insert(int item, int position){
if(first == null || position ==0){
addFirst(item);
return;
}
IntNode currentNode = first;
while(position>1 && currentNode.next != null){
position--;
currentNode = currentNode.next;
}
IntNode newNode = new IndNode(item, currentNode.next);
currentNode.next = newNode;
}
参考答案链接:solution of discussion3
reverse的两种方法非常实用。
SLList == IntList