查找链表中倒数第k个结点

package structure.list;

import structure.list.node.LNode_01;

/**
 * 查找链表中倒数第k个结点
 * 
 * @author Toy
 * 
 */
public class List_K {

	/**
	 * 使用count计数,slow离fast距离k个
	 * 
	 * @param head
	 * @param k
	 * @return
	 */
	public LNode_01 listk_01(LNode_01 head, int k) {
		LNode_01 fast = head;
		LNode_01 slow = null;

		int count = 0;// 记录划过多少节点
		while (fast != null) {

			if (count == k - 1) {
				slow = head;
			} else if (count > k - 1) {
				slow = slow.next;
			}

			fast = fast.next;
			count++;

		}
		System.out.println("list size is: " + count);
		return slow;
	}

	/**
	 * 使用count计数,遍历两次
	 * 
	 * @param head
	 * @param k
	 * @return
	 */
	public LNode_01 listk_02(LNode_01 head, int k) {
		LNode_01 fast = head;

		int count = 0;// 记录节点总数
		while (fast != null) {
			count++;
			fast = fast.next;
		}
		System.out.println("list size is: " + count);

		count = count - k + 1;// 需要遍历的节点数
		if (count < 0) {
			System.out.println("invalid k: " + k);
			return null;
		}
		fast = head;
		while (fast != null) {
			count--;
			if (count == 0) {
				break;
			}
			fast = fast.next;
		}

		return fast;
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		List_K lk = new List_K();
		LinkList_01 list = new LinkList_01();
		list.creat();
		list.show();
		LNode_01 n = lk.listk_01(list.header, 2);
		if (n == null) {
			System.out.println("don't exist ");
		} else {
			System.out.println(n.data);
		}
		
		n = lk.listk_02(list.header, 2);
		if (n == null) {
			System.out.println("don't exist ");
		} else {
			System.out.println(n.data);
		}
	}

}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值