查找单链表中的倒数第k个节点

思路:

	  1.获取单链表的总个数;
      2.总个数与K之差即为从头结点开始计数的第()个节点;
      3.遍历获取倒数第k个节点;

代码实现:

 				//查找单链表中的倒数第k个节点
				    public int getRecipNode(int k) {
				        if (HeadNode.next == null) {
				           throw new RuntimeException("链表为空");
				        }
				        Node temp = HeadNode.next;
				        //获取链表结点的总个数,减去倒数K,就是第()个节点
				        int num = getNodeNum()-1;
				        num = num - k;
				        int count = 0;//计数
				        int no = 0;
				        while (true) {
				            if (count == num) {
				                no = temp.no;
				                break;
				            }
				            count++;
				            temp = temp.next;
				        }
				        return no;
				    }
				     //求单链表中结点的个数
				    public int getNodeNum() {
				        int num = 0;
				        Node temp = HeadNode;
				        while (true) {
				            if (temp.next == null) {
				                num++;
				                break;
				            }
				            num++;
				            temp = temp.next;
				        }
				
				        return num;
				    }

猜你喜欢

转载自blog.csdn.net/qq_44895397/article/details/106062583