cci-Q2.3 只给出中间节点,删除链表中间节点

该博客介绍了一种算法,用于在只提供中间节点的情况下删除单链表中的中间节点。例如,给定链表a->b->c->d->e的中间节点c,删除后链表变为a->b->d->e。
摘要由CSDN通过智能技术生成

原文:

Implement an algorithm to delete a node in the middle of a single linked list, given only access to that node.

EXAMPLE

Input: the node ‘c’ from the linked list a->b->c->d->e Result: nothing is returned, but the new linked list looks like a->b->d->e

译文:

实现一个算法来删除单链表中间的一个结点,只给出指向那个结点的指针。

例子:

输入:指向链表a->b->c->d->e中结点c的指针

结果:不需要返回什么,得到一个新链表:a->b->d->e

只给出中间节点的地址,可以将mid.next的data给mid,然后删除mid.next。

    public static boolean delMidNode(LinkedListNode mid) {
        if (mid == null || mid.next == null) {
            return false;
        }
        LinkedListNode midNext = mid.next;
        mid.data = midNext.data;
        mid.next = midNext.next;
        return true;
    }

testcase

   public static void main(String args[]) {
        LinkedListNode head = null;
        LinkedListNode tmp = null;
        int a[] = {1, 2, 1};
        for (int i = 0; i < a.length; i++) {
            LinkedListNode next = new LinkedListNode(a[i]);
            if (i == 0) {
                head = tmp = next;
                continue;
            }
            tmp.next = next;
            tmp = next;
        }

        // Print the list(before) 
        tmp = head;
        while (tmp != null) {
            System.out.println(tmp.data);
            tmp = tmp.next;
        };

        LinkedListNode mid = head.next;

        delMidNode(mid); // Print the list(before) 

        while (head != null) {
            System.out.println(head.data);
            head = head.next;
        };
    }



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值