您的位置:首页 > 其它

链表中倒数第k个结点

2015-05-31 22:08 225 查看
题目:输入一个链表,输出该链表中倒数第k个结点。为了符合大多数人的习惯,本题从1开始计数,即链表尾结点是倒数第1个结点。例如一个链表有6个结点,从头结点开始它们的值依次是1,2,3,4,5,6.这倒数第3个结点的值是4。

 链表的定义:

class LNode { // 单链表的存储结构
int value;
LNode next;

public LNode() {
}

public LNode(int value) {
this.value = value;
this.next = null;
}

public LNode(int value, LNode next) {
this.value = value;
this.next = next;
}
}
完整性代码为:

package LinkList;

public class FindKthToTailMain {
public LNode head = new LNode();// 创建空的头节点

public void insertHead(int value) { // 插入节点,从头开始
LNode link = new LNode(value); // 创建一个带value值的节点
link.next = head.next;
head.next = link;
}

public LNode findKthToTail(LNode node, int k) {
if (node == null || k <= 0)
return null;
LNode pAhead = node;// 指向头结点
LNode pBehind = node.next;// 这个指向第一个元素
for (int i = 0; i < k; i++) {
if (pAhead.next != null)
pAhead = pAhead.next;
else
return null;

}
System.out.println(pAhead.value);
while (pAhead.next != null) {
pAhead = pAhead.next;
pBehind = pBehind.next;

}
return pBehind;

}

public void print() {
LNode node = head.next;
while (node != null) {
System.out.print(node.value + " ");
node = node.next;
}

}

public static void main(String[] args) {

FindKthToTailMain findKthToTailMain = new FindKthToTailMain();
for (int i = 1; i <= 18; i++) {
findKthToTailMain.insertHead(i);

}
findKthToTailMain.print();
System.out.println();
LNode node = findKthToTailMain.findKthToTail(findKthToTailMain.head, 8);
System.out.println(node.value);

}

}
输出的结果为:

18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 

11

8
题目:求链表的中间结点。如果链表的结点数为奇数,返回中间结点。如果是偶数,返回中间任意一个节点。

分析:可以用两个指针,同时从链表开头出发,一个指针一次走一步,另一个指针一次走两步。当走得快的指针走到链表尾部时,走得慢的指针正好在链表中间。

代码为:

public LNode findMid(LNode node) {
if (node == null)
return null;
LNode pMid = node.next;
if (pMid.next == null)
return pMid;
LNode pfirst = node.next;
while (pfirst != null) {
if (pfirst.next == null)
return pMid;
else {
pfirst = pfirst.next.next;
pMid = pMid.next;
}

}

return pMid;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: