剑指Offer_编程题14:链表中倒数第k个结点

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

牛客网:链接

结点是既有value值,又有指针。

我们可以定义两个指针。第一个指针从链表的头指针开始遍历向前走k-1,第二个指针保持不动;从第k步开始,第二个指针也开始从链表的头指针开始遍历。由于两个指针的距离保持在k-1,当第一个(走在前面的)指针到达链表的尾结点时,第二个指针(走在后面的)指针正好是倒数第k个结点。

效果示意图,以链表总共6个结点,求倒数第3个结点为例:

# -*- coding:utf-8 -*-
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def FindKthToTail(self, head, k):
        # write code here
        if not head or k == 0:
            return None
        phead = head
        ptail = head
        ''' k-1 要注意 '''
        for i in range(k-1):
            if phead.next == None:
                return None
            else:
                phead = phead.next
        
        ''' 循环条件是.next不为空 '''
        while phead.next:
            phead = phead.next
            ptail = ptail.next 

        return ptail

列表是可以存储结点的!但是一定要判断k的大小,大于list长度或者为0都是不可以的。

# -*- coding:utf-8 -*-
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def FindKthToTail(self, head, k):
        # write code here
        l = []
        while head:
            l.append(head)
            head = head.next
        if len(l) < k or k < 1:
            return None
        return l[-k]

胖胖给写的创建列表:

# -*-coding:utf-8 -*-
class ListNode:
	def __init__(self, x):
		self.val = x
		self.next = None

if __name__ == '__main__':
	# 创建链表
	a = [1,2,3]

	# 创建链表
	tmp = ListNode(a[0])
	head = tmp
	for each in a[1:]:
		tmp.next = ListNode(each)
		tmp = tmp.next

	# 遍历链表
	while head:
		print(head.val)
		head = head.next

猜你喜欢

转载自blog.csdn.net/mengmengdajuanjuan/article/details/81041784