0
点赞
收藏
分享

微信扫一扫

查找倒数第K个节点---单链表解决《Java代码实现》

时光已翩然轻擦 2022-03-11 阅读 85

一、实现思想

1.计算出链表的有效长度getValidNumber()
2.遍历链表 ,遍历getValidNumber()-k次,找到节点

二、实现代码

节点类:
		class Node{
		
		    public int no; //data域
		
		    public Node next;
		    
		    public Node(int no) {
		        this.no = no;
		    }
		}

链表类:	
		class LinkedList{
		    public Node head=new Node(0);
		
		    //显示节点
		    public void showQueue(){
		
		        if (head.next==null){
		            System.out.println("链表为空!");
		            return;
		        }
		
		        Node temp=head.next; //辅助变量
		
		        while (temp!=null){
		            System.out.print(temp.no+" ");
		            temp=temp.next;
		        }
		    }
		
		    //添加节点
		    public void addNode(Node node){
		        Node temp=head;
		        while (true){
		            if (temp.next==null){
		                node.next=temp.next;
		                temp.next=node;
		                break;
		            }
		            temp=temp.next;
		        }
		    }
		
		    //计算链表的有效个数
		    public int getValidNumber(){
		
		        if (head.next==null){
		            return 0;
		        }
		
		        int number=0;
		        Node temp=head.next;
		
		        while (temp!=null){
		            number++;
		            temp=temp.next;
		        }
		        return number;
		    }
		
		    //查找倒数第k个节点
		    public Node getLastNode(int k){
		        if (head.next==null||k<1||k>getValidNumber()){ //这里表示参数
		            throw new RuntimeException("参数有误!");
		        }
		
		        Node temp=head.next;
		
		        for (int i = 0; i <getValidNumber()-k ; i++) {
		            temp=temp.next;
		        }
		        return temp;
		    }
		}

测试:
		 public static void main(String[] args) {
		        LinkedList linkedList=new LinkedList();
		        Node n1=new Node(1);
		        Node n2=new Node(2);
		        Node n3=new Node(3);
		        Node n4=new Node(4);
		        linkedList.addNode(n1);
		        linkedList.addNode(n2);
		        linkedList.addNode(n3);
		        linkedList.addNode(n4);
		        linkedList.showQueue();
		        System.out.println("");
		        System.out.println(linkedList.getLastNode(4).no);
		    }	
举报

相关推荐

0 条评论