美文网首页
单链表经典例题_删除任意结点

单链表经典例题_删除任意结点

作者: 掌灬纹 | 来源:发表于2019-04-06 10:43 被阅读0次

题目源自CC150原题为实现一个算法,删除单向链表中的某个结点,
假定你只能访问该结点
* 例如:1->2->3->4->5->null, 给定结点4
* 输出:1->2->3->5->null
很经典的例题,书中介绍的方法也很巧妙,思路是后继结点内容覆盖当前结点,跨过后继结点;

private static boolean removeNode(Node node) {
        if(node.next == null)
            return false;
        node.data = node.next.data;//用原来后继结点内容覆盖当前结点
        node.next = node.next.next;//跨过原来的后继结点,相当于删除了当前结点
        return true;
    }

只是在删除尾结点时,无法依靠题目所给完成题目要求,所以如果删除的是尾结点应返回false

Java代码实现及效果图

image.png
public class RemoveNode {
    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4, 5};
        Node head = new Node(0);
        Node p = head;
        for (int i = 0; i < arr.length; i++) {
            p.next = new Node(arr[i]);
            p = p.next;
        }
        
        print(head);
        Node node = head.next.next.next.next;//模拟第四个结点
        if(removeNode(node))
            print(head);
        else
            System.out.println(removeNode(node));
        
    }
    
    private static boolean removeNode(Node node) {
        if(node.next == null)
            return false;
        node.data = node.next.data;//用原来后继结点内容覆盖当前结点
        node.next = node.next.next;//跨过原来的后继结点,相当于删除了当前结点
        return true;
    }

    private static void print(Node head) {
        Node p = head.next;
        while(p != null) {
            System.out.print(p.data + "->");
            p = p.next;
        }
        System.out.println("null");
        
    }

    private static class Node{
        int data;
        Node next;
        public Node(int data) {
            super();
            this.data = data;
        }
        
    }

}

相关文章

网友评论

      本文标题:单链表经典例题_删除任意结点

      本文链接:https://www.haomeiwen.com/subject/llxriqtx.html