微软算法100题13 查找单向链表倒数第K个节点

第13 题:
题目:输入一个单向链表,输出该链表中倒数第k个结点。链表的倒数第0 个结点为链表的尾指针

 

思路:先遍历链表,求得总节点数N,则倒数第K个节点是正数N-K,时间复杂度为o(N+N-K)

 

 1 package com.rui.microsoft;
 2 
 3 public class Test13_FindKthNodeFromBack {
 4 
 5     public static void main(String[] args) {
 6         Node node1 = new Node(1);
 7         Node node2 = new Node(2);
 8         Node node3 = new Node(3);
 9         Node node4 = new Node(4);
10         Node node5 = new Node(5);
11         
12         node1.next = node2;
13         node2.next = node3;
14         node3.next = node4;
15         node4.next = node5;
16         
17         Node node = Test13_FindKthNodeFromBack.getKthFromBack(node1, 3);
18         System.out.println(node.value);
19     }
20     
21     public static Node getKthFromBack(Node head, int k){
22         Node node = head;
23         if(null == node)return null;
24         int size = 0;
25         while(null != node){
26             node = node.next;
27             size++;
28         }
29         
30         int pos = size - k;
31         if(pos < 0) return null;
32         
33         //put pointer to the head again
34         int i = 0;
35         node = head;
36         while(i < pos){
37             node = node.next;
38             i++;
39         }
40         return node;
41     }
42     
43     static class Node{
44         int value;
45         Node next;
46         Node(int v){
47             this.value = v;
48         }
49     }
50 }

 

posted @ 2015-10-23 16:55  蟹粉小笼包  阅读(183)  评论(0编辑  收藏  举报