連結串列的初始化以及查詢連結串列中倒數第k個節點的值
阿新 • • 發佈:2018-12-19
package com.xhy.stackandqueue;
public class LinkedList {
public static class Node {
int value;
Node next;
public Node(int value) {
this.value=value;
}
}
public Node head;
public Node current;
public void add(int data) {
//如果頭結點為空,為頭結點
if(head == null) {
head = new Node(data);
current = head;
} else {
current.next = new Node(data);
current = current.next;
}
}
//初始化連結串列,並且返回表頭
public Node init() {
for(int i=0; i<9; i++) {
this.add(i);
}
return head;
}
/**
* 輸入一個鍵表,輸出該連結串列中倒數第k 個結點.為了符合大多數人的習慣,
* 本題從1開始計數,即連結串列的尾結點是倒數第1個結點.例如一個連結串列有6個結點,
* 從頭結點開始它們的值依次是1、2、3、4、5 6。這個連結串列的倒數第3個結點是值為4的結點.
*
* @param head 連結串列的頭結點
* @param k 倒數第k個結點
* @return 倒數第k個結點
*/
public static Node findKthToTail(Node head, int k) {
// 輸入的連結串列不能為空,並且k大於0
if (k < 1 || head == null) {
return null;
}
// 指向頭結點
Node pointer = head;
// 倒數第k個結點與倒數第一個結點相隔k-1個位置
// pointer先走k-1個位置
for (int i = 1; i < k; i++) {
// 說明還有結點
if (pointer.next != null) {
pointer = pointer.next;
}
// 已經沒有節點了,但是i還沒有到達k-1說明k太大,連結串列中沒有那麼多的元素
else {
// 返回結果
return null;
}
}
// pointer還沒有走到連結串列的末尾,那麼pointer和head一起走,
// 當pointer走到最後一個結點即,pointer.next=null時,head就是倒數第k個結點
while (pointer.next != null) {
head = head.next;
pointer = pointer.next;
}
// 返回結果
return head;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
LinkedList linkedList=new LinkedList();
Node head = linkedList.init();
Node findNode = findKthToTail(head, 5);
System.out.println(findNode.value);
}
}