题目
编写一个方法insertAfter(),接受两个链表结点作为参数,将第二结点插入链表并使之成为第一个结点的后续结点(如果两个参数为空则什么也不做)。
分析
题目翻译的有问题
比如有列表a-b-c-d-e-f
方法接受2个参数(c,x)
将列表修改为a-b-c-x-d-e-f
根据oldNode找到current
然后就是各种指定next
Node next=current.next;
current.next=newNode;
newNode.next=next;
java代码
package hk13;
import java.util.Iterator;
/**
* @description: ${description}
* @create: 2019-02-18
**/
public class W_1_3_25<Item> implements Iterable {
private static class Node<Item>{//改成静态的
Item item;
Node next;
}
private Node first;//栈顶,最近添加元素,也是个类,有两个属性
private int n;//元素数量,类似指针
public void push(Item item){
Node old=first;
first=new Node();
first.item=item;
first.next=old;
n++;
}
public Item pop(){
n--;
Item item = (Item) first.item;//多了个强转 为什么呢???
first=first.next;
return item;
}
//1.3.25
public void insertAfter(Node newNode,Node oldNode){
Node current=first;
while ((current.next!=null)){
if(oldNode.item.equals(current.item)){
break;
}
current=current.next;
}
Node next=current.next;
current.next=newNode;
newNode.next=next;
// newNode.next=oldNode.next;
// oldNode.next=newNode;
}
public static void printList(W_1_3_25 a){
for (Object o:a
) {
System.out.println(o);
}
}
public int size(){
return n;
}
public boolean isEmpty(){
return n==0;
}
@Override
public Iterator iterator() {
return new ListIterator();
}
private class ListIterator implements Iterator<Item>{
private Node current=first;
@Override
public boolean hasNext() {
return current!=null;
}
@Override
public Item next() {
Item item = (Item) current.item;
current=current.next;
return item;
}
@Override
public void remove() {
//blank
}
}
public static void main(String[] args) {
W_1_3_25<String> linkedList=new W_1_3_25<String>();
linkedList.push("d");
linkedList.push("c");
linkedList.push("b");
linkedList.push("a");
printList(linkedList);
Node<String> b = new Node<String>();
b.item="b";
Node<String> x = new Node<String>();
x.item="x";
System.out.println("-------");
linkedList.insertAfter(x,b);
printList(linkedList);
}
}
运行结果
心得
题目翻译的有问题的话 可以看看英文原版的
有一些判断就没去做了.
比如oldnode不在LinkedList里面,或者有的是null的就不做了