第2关:单循环链表的实现—链表的删除,任务描述在上一关,我们已经完成了单循环链表的添加、遍历功能,我们已经可以向表中添加数据并输出,现在我们将要实现其删除功能。本关任务:删除循环链表中指定位置的

第2关:单循环链表的实现—链表的删除

200

  • 任务要求
  • 参考答案
  • 评论42

任务描述

在上一关,我们已经完成了单循环链表的添加、遍历功能,我们已经可以向表中添加数据并输出,现在我们将要实现其删除功能。

本关任务:删除循环链表中指定位置的结点,并返回其值。

相关知识

单循环链表删除操作

单循环链表的删除操作与普通的单链表操作基本类似,通过遍历找到要删除结点的直接前驱,然后改变前驱的链接情况。如下图:

这里删除的是尾结点,由于我们在构建单循环链表时是用tail指向尾结点的,所以在删除尾结点后需改变tail的指向,如果删除的不是尾结点则不需改变tail指向。

编程要求

本关的编程任务是补全右侧代码片段中BeginEnd中间的代码,具体要求如下:

  • 完成删除指定位置index处结点,并返回其值。

具体请参见后续测试样例。

本关涉及的代码文件MyCircleLinkedList.java的代码框架如下:

package step2;
 
/**
 * Created by sykus on 2018/1/15.
 */
public class MyCircleLinkedList {
    private Node head;//头结点, 不存数据
    private Node tail;//尾结点, 指向链表的最后一个节点
    private int size;
 
    public MyCircleLinkedList() {
        head = new Node(Integer.MIN_VALUE, null);
        head.next = head;
        tail = head;
        size = 0;
    }
 
    /**
     * 添加到链表尾部
     *
     * @param item
     */
    public void add(int item) {
        Node node = new Node(item, tail.next);
        tail.next = node;
        tail = node;
        ++size;
 
    }
 
    /**
     * 遍历链表并输出元素
     */
    public void output() {
        Node p = head;
        while (p.next != head) {
            p = p.next;
            System.out.println(p.item);
        }
    }
 
 
    /**
     * 删除从头结点开始的第index个结点
     * index从0开始
     *
     * @param index
     * @return
     */
    public int remove(int index) {
        checkPosIndex(index);
 
        /********** Begin *********/
          Node f = head;
            while ((index--) > 0) {
                f = f.next;
            }
            Node del = f.next;
            if (del == tail) {
                tail = f;
            }
            f.next = del.next;
            del.next = null;
            int oldVal = del.item;
            del = null;
            --size;
            return oldVal;
 
 
 
        /********** End *********/
    }
 
    public boolean isEmpty() {
        return head.next == head;
    }
 
    public int size() {
        return size;
    }
 
    private void checkPosIndex(int index) {
        if (index < 0 || index >= size) {
            throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
        }
    }
 
    //结点内部类
    private static class Node {
        int item;
        Node next;
 
        Node(int item, Node next) {
            this.item = item;
            this.next = next;
        }
    }
}
//智科01班 421045   (感谢内生原动力 四阿哥108)

加油 冲冲冲    三创赛组队 有?

//智科01班 421045   (感谢内生原动力 四阿哥108)

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值