小蜗牛1990 2016-01-22 02:52 采纳率: 50%
浏览 1413
已采纳

有关java的白痴问题,希望大神回答

Write a function to delete a node (except the tail) in a singly linked list, given only access to that node.

Supposed the linked list is 1 -> 2 -> 3 -> 4 and you are given the third node with value 3, the linked list should become 1 -> 2 -> 4 after calling your function.

/**

  • Definition for singly-linked list.
  • public class ListNode {
  • int val;
  • ListNode next;
  • ListNode(int x) { val = x; }
  • } */ public class Solution { public void deleteNode(ListNode node) { node=node.next; } } 不明白为什么这么赋值不可以。可不可以有大神系统的从原理讲解一下。
  • 写回答

6条回答

  • 毕小宝 博客专家认证 2016-01-22 09:08
    关注

    可以直接赋值的,因为你的ListNode的成员变量都是default权限即包内访问的,只要你的ListNode和Solution类在同一个包里面就可以了。
    你的删除方法有问题,先要查找到待删除节点,然后再删除。修正你的Solution代码如下:

     public class Solution {
        public void deleteNode(ListNode list,ListNode node) {
            //空链表
            if(node==null||list==null||list.getNext()==null){
                return ;
            }
    
            //查找node节点
            ListNode curNode = list;
            ListNode preNode = null;
            ListNode next = list.next;
            while(curNode!=null){
                if(curNode.val==node.val){//找到
                    System.out.println("找到待删除对象了。"+node.val);
                    break;
                }
                preNode = curNode;
                curNode = next;
                next = next.next;
            }
    
    
            //删除node节点 
            if(preNode==null){
                //第一个元素删除操作直接修正list为next:curNode-next
                list = next;
            }else{
                //删除中间节点中间:preNode-curNode-next
                preNode.next = next;
            }
        }
    
        public void printListNode(ListNode list){
            ListNode node = list;
            while(node!=null){
                System.out.println(node.val);
                node = node.next;
            }
        }
    
        public static void main(String[] args) {
            ListNode n1 = new ListNode(1);
            ListNode n2 = new ListNode(2);
            ListNode n3 = new ListNode(3);
            ListNode n4 = new ListNode(4);
            n1.setNext(n2);
            n2.setNext(n3);
            n3.setNext(n4);
            n4.setNext(null);
            Solution s = new Solution();
            s.printListNode(n1);
            s.deleteNode(n1, n3);
            s.printListNode(n1);
        }
    }
    

    Ok,测试结果

     1
    2
    3
    4
    找到待删除对象了。3
    1
    2
    4
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(5条)

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘