给定一个链表的表头,如果链表节点数为奇数则返回中间的节点,否则返回中间两个节点的任意一个
# -*- coding: utf-8 -*-
# @Time : 2019-04-23 17:24
# @Author : Jayce Wong
# @ProjectName : job
# @FileName : findMidNode.py
# @Blog : http://blog.51cto.com/jayce1111
# @Github : https://github.com/SysuJayce
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def FindKthToTail(head):
"""
使用快慢指针,慢指针走1步,快指针走2步。当快指针指向尾节点的时候,慢指针所在的节点就是所求
:param head:
:return:
"""
if not head:
return None
fast = slow = head
while fast.next:
fast = fast.next
slow = slow.next
if fast.next:
fast = fast.next
return slow
def main():
zero = ListNode(0)
one = ListNode(1)
two = ListNode(2)
three = ListNode(3)
four = ListNode(4)
zero.next = one
one.next = two
two.next = three
three.next = four
print(FindKthToTail(zero).val)
if __name__ == '__main__':
main()