题目:输入一个链表,输出该链表中倒数第 k 个结点。为了符合大多数人的习惯,
本题从 1 开始计数,即链表的尾结点是倒数第一个结点。例如一个有 6 个结点的
链表,从头结点依次是 1,2,3,4, 5,6。倒数第三个结点就是值为 4 的结点。
搜出的参考代码:
public class Problem15 {
public static void main(String[] args) {
ListNode head=new ListNode();
ListNode second=new ListNode();
ListNode third=new ListNode();
ListNode forth=new ListNode();
head.nextNode=second;
second.nextNode=third;
third.nextNode=forth;
head.data=1;
second.data=2;
third.data=3;
forth.data=4;
Problem15 test=new Problem15();
ListNode resultListNode=test.findKToTail(head, 3);
System.out.println(resultListNode.data);
}
public ListNode findKToTail(ListNode head,int k){
if(head==null||k==0){
return null;
}
ListNode resultNode=null;
ListNode headListNode=head;
for(int i=0;i<k;++i){
if(headListNode.nextNode!=null){
headListNode=headListNode.nextNode;
}else{
return null;
}
}
resultNode=head;
while(headListNode!=null){
resultNode=resultNode.nextNode;
headListNode=headListNode.nextNode;
}
return resultNode;
}
}
public class ListNode
{
int data;
ListNode nextNode;
}
如果取極端條件,比如:k=連表長度,會出錯
由此,在ListNode類中增加一個前一個結點屬性。
public class ListNode {
int data;
ListNode nextNode;
ListNode preNode;
}
主函數:
public class LastKNode {
public static void main(String[] args) {
ListNode head = new ListNode();
ListNode second = new ListNode();
ListNode third = new ListNode();
ListNode forth = new ListNode();
ListNode tail = new ListNode();
head.nextNode = second;
second.nextNode = third;
third.nextNode = forth;
forth.nextNode = tail;
head.data = 1;
second.data = 2;
third.data = 3;
forth.data = 4;
tail.data = 5;
tail.preNode = forth;
forth.preNode = third;
third.preNode = second;
second.preNode = head;
LastKNode lkn = new LastKNode();
ListNode rst = lkn.findKToTail(head, 5);
System.out.println(rst.data);
}
public ListNode findKToTail(ListNode head, int k) {
if (head == null || k == 0)
return null;
ListNode resultNode = null;
ListNode headListNode = head;
//
ListNode tail = null;
while(headListNode.nextNode!=null) {
headListNode = headListNode.nextNode;
}
tail=headListNode;
for(int i=0;i<k-1;i++) {
tail = tail.preNode;
}
resultNode=tail;
/*
//正数K个node
for (int i = 0; i < k; ++i) {
if (headListNode.nextNode != null) {
headListNode = headListNode.nextNode;
} else {
return null;
}
}
//
resultNode = head;
while (headListNode != null) {
resultNode = resultNode.nextNode;
headListNode = headListNode.nextNode;
}
*/
return resultNode;
}
}
問題:
爲何ListNode Class中只設下一個節點,不設上一個節點?
解決:
PS:Eclipse的win+shift+f快捷键与win10的微软输入法繁体切换冲突。这...