您的位置:首页 > 其它

Cracking the coding interview--Q2.2

2014-10-30 11:10 288 查看
原文:

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);
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  算法