《算法(第四版)》 习题:1.3.19

1、问题描述

给出一段代码,删除链表的尾结点,其中链表的首结点为first。

2、算法思路

为删除尾结点,需要找到倒数第二个结点。尾节点的标志为last.next==null是否成立,找到尾节点后需将倒数第二个节点SecondLast.next=null即可删除尾节点。

3、编程实现(Java实现)

public class Solution_19 {

    
    public static void main(String[] args){
        String[] strs = {"You","are","a", "good" , "boy"};
        Node first = creatList(strs); //建立一个链表        
        System.out.println("删除最后一个节点之前链表为:");
        printList(first);  //打印原始链表
        delLastNode(first);  //删除最后一个节点
        System.out.println("删除最后一个节点之后链表为:");
        printList(first);        //打印删除节点后链表
    }
    /*
     * 节点内部类
     */
    private class Node{
        String item;
        Node next;
    }
    /**
     * 建立以字符数组值的链表,数组至少需要一个元素
     * @param strs
     * @return firstNode
     */
    public static Node creatList(String[] strs){    
        /*
         * 建立头结点
         */
        Solution_19 solution = new Solution_19();
        Node newnode = solution.new Node();
        newnode.item = strs[0];
        Node first = newnode;
        
        /*
         * 建立后续节点
         */
        Node current = first;    
        for(int i=1;i<strs.length;i++){
            newnode = solution.new Node();
            newnode.item = strs[i];
            current.next = newnode;
            current = newnode;
        }    
        current.next=null;//尾节点指针指向null
        return first;
    }
    /**
     * 删除最后一个节点
     * @param first
     */
    public static void delLastNode(Node first){
        if(first.next==null) first = null;  //如果只有一个节点,则最后一个节点就是本身
        else{        //如果有两个或两个以上节点,就需要查找最后一个节点,以及记录倒数第二个节点
            Node current = first;
            Node SecondLast = first;
            while(current.next!=null){    
                SecondLast = current;
                current = current.next;
            }
            SecondLast.next = null;//删除链表的尾节点,即把倒数第二个节点的指针指向Null即可
        }
    }        
    /**
     * 打印首节点first的链表
     * @param first
     */
    private static void printList(Node first){
        System.out.println(first.item);//打印头节点
        Node current = first;
        while(current.next!=null){            
            current = current.next;
            System.out.println(current.item);
        }
    }
    

}

4、测试结果



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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值