Cracking the coding interview--Q2.2

原文:

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

译文:

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


package chapter_2_LinkedLists;

import java.util.Scanner;

/**
 * 实现一个算法从一个单链表中返回倒数第n个元素。
 */
public class Question_2_2 {
	
	/**
	 * 如果提前知道链表的长度,可以直接计算正向位置
	 */
	public static int findNthLast(LinkList linkList, int n) {
		Node p;
		p = linkList.head;
		if(n > linkList.size) {
			return -1;
		}		
		int locat = linkList.size - n + 1;
		int i = 1;
		boolean flag = true;
		while(flag) {
			if(i != locat) {
				i++;
				p = p.next;
			} else {
				flag = false;
			}
		}
		return p.data;
	}
	
	/**
	 * ********
	 * 如果提前不知道链表的长度,可以使用两个指针,间距保持n,只需要扫描一遍
	 */
	public static int findNthLast2(LinkList linkList, int n) { 
		Node p, q;
		p = linkList.head;
		int i = 1;
		q = p;
		while(i != n && q != null) {
			q = q.next;
			i ++;
		}
		if(q == null) {
			return -1;
		}
		// 上面步骤保持n-1,开始往后移动
		while(q.next != null) {
			q = q.next;
			p = p.next;
		}
		return p.data;
	}
	
	public static void main(String args[]) {
		
		Scanner scanner = new Scanner(System.in);
		LinkList linkList = new LinkList();
		int temp;
		int num = scanner.nextInt();
		for(int i=0; i< num; i++) {
			temp = scanner.nextInt();
			linkList.add(temp);
		}
		scanner.nextLine();
		int n = scanner.nextInt();
		
		int result = findNthLast2(linkList, n);
		if(result < 0) {
			System.out.format("error : %3d\n", result);
		} else {
			System.out.format("%3d\n", result);
		}
	}
}



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值