Cracking the coding interview--Q2.2

本文详细介绍了如何通过编程实现在单链表中找到倒数第n个元素的方法,并提供了相应的代码实现。代码示例清晰易懂,适合初学者理解和实践。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目

原文:

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

译文:

实现一个算法找出一个单链表的倒数第n个元素。

解答

代码如下:

import java.util.*;

class Q2_2{
	public static Object nthtoLastNode(LinkList ll,int n) {
		Node head=ll.head;
		Node node = head;
		int count=n-1; 
		while (count >= 1 && node.next != null) {
			count--;
			node = node.next;
		}
		//链表的长度小于n
		if (count != 0) return null;
		
		while (node.next != null) {
			head = head.next;
			node = node.next;
		}
		return head.data;
	}
	public static void main(String[] args){
		int[] data=new int[]{1,2,3,2,5,2};
		
		LinkList ll=new LinkList();
		for(int i=0;i<data.length;i++){
			ll.add(data[i]);
		}
		
		System.out.println(nthtoLastNode(ll,4));
	}
}

class Node{
	public Object data;
	public Node next;
	
	public Object getData() {
		return data;
	}
	public void setData(Object data) {
		this.data = data;
	}
	public Node getNext() {
		return next;
	}
	public void setNext(Node next) {
		this.next = next;
	}
}	
	
class LinkList{
	public Node head;
    public Node tail;
    private int size;
	public int getSize() {
		return size;
	}
	public void setSize(int size) {
		this.size = size;
	}
    
	public void add(Object i){//在链表结尾插入节点
		Node newnode = new Node();
		newnode.setData(i);
		if(head == null){
			head = newnode;
			tail = newnode;
			size ++ ;
		}
		else {
			tail.setNext(newnode);
			tail = newnode;
			size ++ ;
		}
	}
}

---EOF---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值