链表中倒数第k个结点

题目:输入一个链表,输出该链表中倒数第k个结点。为了符合大多数人的习惯,本题从1开始计数,即链表尾结点是倒数第1个结点。例如一个链表有6个结点,从头结点开始它们的值依次是1,2,3,4,5,6.这倒数第3个结点的值是4。

 链表的定义:

class LNode { // 单链表的存储结构
	int value;
	LNode next;

	public LNode() {
	}

	public LNode(int value) {
		this.value = value;
		this.next = null;
	}

	public LNode(int value, LNode next) {
		this.value = value;
		this.next = next;
	}
}
完整性代码为:

package LinkList;

public class FindKthToTailMain {
	public LNode head = new LNode();// 创建空的头节点

	public void insertHead(int value) { // 插入节点,从头开始
		LNode link = new LNode(value); // 创建一个带value值的节点
		link.next = head.next;
		head.next = link;
	}

	public LNode findKthToTail(LNode node, int k) {
		if (node == null || k <= 0)
			return null;
		LNode pAhead = node;// 指向头结点
		LNode pBehind = node.next;// 这个指向第一个元素
		for (int i = 0; i < k; i++) {
			if (pAhead.next != null)
				pAhead = pAhead.next;
			else
				return null;

		}
		System.out.println(pAhead.value);
		while (pAhead.next != null) {
			pAhead = pAhead.next;
			pBehind = pBehind.next;

		}
		return pBehind;

	}

	public void print() {
		LNode node = head.next;
		while (node != null) {
			System.out.print(node.value + " ");
			node = node.next;
		}

	}

	public static void main(String[] args) {

		FindKthToTailMain findKthToTailMain = new FindKthToTailMain();
		for (int i = 1; i <= 18; i++) {
			findKthToTailMain.insertHead(i);

		}
		findKthToTailMain.print();
		System.out.println();
		LNode node = findKthToTailMain.findKthToTail(findKthToTailMain.head, 8);
		System.out.println(node.value);

	}

}
输出的结果为:

18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 
11
8
题目:求链表的中间结点。如果链表的结点数为奇数,返回中间结点。如果是偶数,返回中间任意一个节点。

分析:可以用两个指针,同时从链表开头出发,一个指针一次走一步,另一个指针一次走两步。当走得快的指针走到链表尾部时,走得慢的指针正好在链表中间。

代码为:

	public LNode findMid(LNode node) {
		if (node == null)
			return null;
		LNode pMid = node.next;
		if (pMid.next == null)
			return pMid;
		LNode pfirst = node.next;
		while (pfirst != null) {
			if (pfirst.next == null)
				return pMid;
			else {
				pfirst = pfirst.next.next;
				pMid = pMid.next;
			}

		}

		return pMid;

	}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值