有关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; } } 不明白为什么这么赋值不可以。可不可以有大神系统的从原理讲解一下。

可以直接赋值的,因为你的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

一个是对象的属性,一个是对象,怎么赋值呢

你class的成员怎么可以是自己class类型的呢

线性连表问题,你先把定义搞懂

楼主应该是想实现一个链表吧,但是感觉楼主你的问题没有描述清楚,最好把完整代码,完整报错信息都贴出来。

补充:ListNode类提供next的get/set方法:

    public ListNode getNext(){
        return next;
    }

    public void setNext(ListNode next) {
        this.next = next;
    }