链表中倒数第k个结点(包含测试) java

版权声明:博客内容为本人自己所写,请勿转载。 https://blog.csdn.net/weixin_42805929/article/details/83107972

链表中倒数第k个结点(包含测试) java

题目描述
输入一个链表,输出该链表中倒数第k个结点。

代码:

import java.util.*;
/**
 * 输出链表中的倒数第k个结点
 * @author 娟娟
 *
 */
public class Solution2 {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		String[] st = sc.nextLine().split(" ");
		int k = sc.nextInt();
		if(st.length != 0 && st != null) {
			ListNode start = new ListNode(Integer.parseInt(st[0]));
			ListNode head = start;
			for(int i = 1; i < st.length; i++) {
				start.next = new ListNode(Integer.parseInt(st[i]));
				start = start.next;
			}
			System.out.println(get(head, k).val);
		}else {
			System.out.println("输出的链表为空或者长度为0");
		}
	}
	public static ListNode get(ListNode head, int k) {
		if(head == null || k <= 0) {
			return null;
		}
		ListNode start1 = head;
		ListNode start2 = head;
		for(int i = 1; i < k; i++) {
			if(start1.next != null) {
				start1 = start1.next;
			}else {
				return null;
			}
		}
		for(int j = k; start1.next != null; j++) {
			start1 = start1.next;
			start2 = start2.next;
		}
		return start2;
	}
}

class ListNode{
	int val;
	ListNode next = null;
	
	ListNode(int val){
		this.val = val;
	}
}

其他方法见: https://blog.csdn.net/weixin_42805929/article/details/82990091

猜你喜欢

转载自blog.csdn.net/weixin_42805929/article/details/83107972