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

论坛 期权论坛 编程之家     
选择匿名的用户   2021-6-2 17:57   1026   0

原文:

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 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:3875789
帖子:775174
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP