链表中倒数第k个节点

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

 1 # -*- coding:utf-8 -*-
 2 # class ListNode:
 3 #     def __init__(self, x):
 4 #         self.val = x
 5 #         self.next = None
 6 
 7 class Solution:
 8     def FindKthToTail(self, head, k):
 9         fast = ListNode(0)
10         slow = ListNode(0)
11         if head == None:
12             return None
13         safehead = ListNode(head.val)
14         safehead.next = head.next
15         fast = head
16         count = 0
17         while count != k:
18             if fast == None:
19                 return None
20             fast = fast.next
21             count += 1
22         slow = safehead
23         while fast != None:
24             fast = fast.next
25             slow = slow.next
26         return slow

 

Java版本代码:

 1 class Solution {
 2     public ListNode getKthFromEnd(ListNode head, int k) {
 3         if (head == null) {
 4             return null;
 5         }
 6 
 7         ListNode safeHead = new ListNode(head.val);
 8         safeHead.next = head.next;
 9         ListNode fast = head;
10         int count = 0;
11         while (count != k) {
12             if (fast == null) {
13                 return null;
14             }
15             fast = fast.next;
16             count++;
17         }
18         ListNode slow = safeHead;
19         while (fast != null) {
20             fast = fast.next;
21             slow = slow.next;
22         }
23         return slow;
24     }
25 }

 

posted on 2019-06-12 22:12  Sempron2800+  阅读(113)  评论(0编辑  收藏  举报