描述 |
输入一个单向链表,输出该链表中倒数第k个结点,链表的倒数第0个结点为链表的尾指针。 链表结点定义如下: struct ListNode { int m_nKey; ListNode* m_pNext; }; 详细描述: 接口说明 原型: ListNode* FindKthToTail(ListNode* pListHead, unsignedint k); 输入参数: ListNode* pListHead 单向链表 unsigned int k 倒数第k个结点 输出参数(指针指向的内存区域保证有效): 无 返回值: 正常返回倒数第k个结点指针,异常返回空指针 |
---|---|
知识点 | 链表,查找,指针 |
运行时间限制 | 10M |
内存限制 | 128 |
输入 |
输入说明 |
输出 |
输出一个整数 |
样例输入 | 8 1 2 3 4 5 6 7 8 4 |
样例输出 | 4 |
package com.oj; import java.util.HashMap;
import java.util.Map;
import java.util.Scanner; class Node{
private int data;
private Node next;
private Node pre;
public Node() {
this.next = null;
this.pre = null;
}
public Node(int data) {
this.data = data;
this.next = null;
this.pre = null;
}
public int getData() {
return data;
}
public void setData(int data) {
this.data = data;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
public Node getPre() {
return pre;
}
public void setPre(Node pre) {
this.pre = pre;
}
} class MineList{
private Node head;
private Node rear;
public MineList() {
head = null;
rear = null;
}
public void insertNode(Node node){
if(head==null){
head = node;
rear = node;
}else{
rear.setNext(node);
node.setPre(rear);
rear = node;
}
}
public int getKfromRear(int k){
if(rear!=null){
Node show = rear;
for(int i = 0;i < k;i++){
show = show.getPre();
//System.out.println("hello "+i);
}
return show.getData();
}
return 0;
}
}
public class Test {
public static void test(){
Scanner in = new Scanner(System.in);
String str = in.nextLine();
String[] strdata = str.split(" ");
int length = strdata.length;
int num = Integer.valueOf(strdata[0]);
int k = Integer.valueOf(strdata[length-1]);
int[] data = new int[length-2]; MineList list = new MineList();
for(int i = 1;i <= length-2; i++){
data[i-1] = Integer.valueOf(strdata[i]);
list.insertNode(new Node(data[i-1]));
}
System.out.println(list.getKfromRear(k));
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int num = in.nextInt();
int[] data = new int[num];
for(int i = 0;i < num; i++)
data[i] = in.nextInt();
int k = in.nextInt();
MineList list = new MineList();
for(int i = 0;i < num; i++){
list.insertNode(new Node(data[i]));
}
System.out.println(list.getKfromRear(k));
}
}
题目描述
输入一个链表,输出该链表中倒数第k个结点。
思路:设置两个指针,一个findlast指针,用于查找最后的null;一个findk指针,始终位于 findlast的前k的位置。
/*
public class ListNode {
int val;
ListNode next = null; ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode FindKthToTail(ListNode head,int k) {
if(head==null)
return null;
ListNode findlast = head;
ListNode findk = head; while(findlast!=null){
findlast = findlast.next;
if(k==0)
findk = findk.next;
if(k!=0)
k--;
}
if(k==0)
return findk;
return null;
}
}