LinkLists 链表中返回倒数第n个元素 @CareerCup

原文:

Implement an algorithm to find the nth to last element of a singly linked list.

译文:

实现一个算法从一个单链表中返回倒数第n个元素。

思路:

1 递归(头递归),在递归过程中,递归到倒数第k个时直接打印出来。如果需要保存那个值,则可以建一个wrapper类来存放,或者用全局变量

2 Iterative 双指针,先让快指针超前慢指针k个距离,然后让快慢指针同步往前走,直到快指针碰到链表尾。

package LinkLists;

import CtCILibrary.AssortedMethods;
import CtCILibrary.LinkedListNode;

public class S2_2 {

	// 递归1,直接打出来
	public static int nthToLast(LinkedListNode head, int k) {
		if(head == null) {
			return 0;
		}
		
		int i = nthToLast(head.next, k) + 1;	// 当前倒数等于后一个倒数加上1
		if(i == k) {
			System.out.println(head.data);
		}
		
		return i;
	}
	
	// 递归2,用一个wrapper类,相当于与一个全局变量
	public static LinkedListNode nthToLast2(LinkedListNode head, int k, IntWrapper wrapper) {
		if(head == null) {
			return null;
		}
		LinkedListNode node = nthToLast2(head.next, k, wrapper);
		wrapper.value++;
		if(wrapper.value == k) {
			return head;
		}
		return node;
	}
	
	static class IntWrapper {
		public int value = 0;
	}
	
	// Iterative的方法,双指针,让两个指针间相差k个距离,当快指针走到头时,返回慢指针的位置
	public static LinkedListNode nthToLast3(LinkedListNode head, int k) {
		if(k < 0) {
			return null;
		}
		
		LinkedListNode cur=head, probe=head;
		for(int i=0; i<k-1; i++) {
			if(probe == null) {		// k太大
				return null;
			}
			probe = probe.next;
		}
		
		if(probe == null) {
			return null;
		}
		
		// 两个指针一起往前走,直到probe指针走到头
		while(probe.next != null) {
			cur = cur.next;
			probe = probe.next;
		}
		return cur;
	}
	
	
	public static void main(String[] args) {
		LinkedListNode head = AssortedMethods.randomLinkedList(10, 0, 10);
		System.out.println(head.printForward());
		int nth = 3;
		IntWrapper wr = new IntWrapper();
		nthToLast(head, nth);
		LinkedListNode n = nthToLast2(head, nth, wr);
		if (n != null) {
			System.out.println(nth + "th to last node is " + n.data);
		} else {
			System.out.println("Null.  n is out of bounds.");
		}
		LinkedListNode n2 = nthToLast3(head, nth);
		System.out.println(n2.data);
	}
	
	
}








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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值