美文网首页
算法-18.删除链表的节点

算法-18.删除链表的节点

作者: zzq_nene | 来源:发表于2020-08-15 19:03 被阅读0次

    给定单向链表的头指针和一个要删除的节点的值,定义一个函数删除该节点。
    返回删除后的链表的头节点。

        public class ListNode {
            int val;
            ListNode next;
    
            ListNode(int x) {
                val = x;
            }
        }
    
        /**
         * 删除链表的节点
         *
         * @param head
         * @param val
         * @return
         */
        public ListNode deleteNode(ListNode head, int val) {
            // 如果head为null,则返回null
            if (head == null) {
                return null;
            }
            // 如果head.next为null,说明就一个
            if (head.next == null) {
                if (head.val == val) {
                    return null;
                }
                return head;
            }
            // 有多个节点,删除头节点
            if (head.val == val) {
                return head.next;
            }
            ListNode cur = head;
            ListNode next = null;
            while (cur.next != null) {
                // 获取next
                next = cur.next;
                // 从第二个节点开始判断,value是否相等
                // 如果不相等,则把当前节点位置向后推一个
                // 如果相等,则删除这个next节点,即将当前节点的next指向next.next
                if (next.val == val) {
                    next = next.next;
                    cur.next = next;
                } else {
                    cur = next;
                }
            }
            return head;
        }
    

    如果是给定一个链表头节点,再给一个需要删除的节点,而不是给val
    比如:

    public ListNode deleteNode(ListNode head, ListNode tobeDelete) {
            if (head == null || tobeDelete == null)
                return null;
            if (tobeDelete.next != null) {
                // 要删除的节点不是尾节点
                // 这样做的目的是因为tobeDelete节点中保存了其val和next信息
                ListNode next = tobeDelete.next;
                tobeDelete.val = next.val;
                tobeDelete.next = next.next;
            } else {
                if (head == tobeDelete)
                    // 只有一个节点
                    head = null;
                else {
                    ListNode cur = head;
                    while (cur.next != tobeDelete)
                        cur = cur.next;
                    cur.next = null;
                }
            }
            return head;
        }
    

    相关文章

      网友评论

          本文标题:算法-18.删除链表的节点

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