算法-第四版-练习1.3.25解答

题目

编写一个方法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的就不做了

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值