【正确答案】方法一:顺序遍历两遍法
主要思路:首先遍历一遍单链表,求出整个单链表的长度n,然后把求倒数第k个元素转换为求顺数第n-k个元素,再去遍历一次单链表就可以得到结果。但是该方法需要对单链表进行两次遍历。
方法二:快慢指针法
由于单链表只能从头到尾依次访问链表的各个结点,因此,如果要找链表的倒数第k个元素,也只能从头到尾进行遍历查找,在查找过程中,设置两个指针,让其中一个指针比另一个指针先前移k步,然后两个指针同时往前移动。循环直到先行的指针值为None时,另一个指针所指的位置就是所要找的位置。程序代码如下:
class LNode:
def __new__(self,x):
self.data=x
self.next=None
# 构造一个单链表
def ConstructList():
i=1
head=LNode()
head.next=None
tmp=None
cur=head
# 构造第一个链表
while i<8:
tmp=LNode()
tmp.data=i
tmp.next=None
cur.next=tmp
cur=tmp
i+=1
return head
# 顺序打印单链表结点的数据
def PrintList(head):
cur=head.next
while cur!=None:
print(cur.data),
cur=cur.next
"""
方法功能: 找出链表倒数第k个结点
输入参数: head:链表头结点
返回值: 倒数第k个结点
"""
def FindLastK(head,k):
if head==None or head.next=None:
return head
slow=LNode()
fast=LNode()
slow=head.next
fast=head.next
i=0
while i<k and fast!=None:
fast=fast.next #移k步
i+=1
if i<k:
return None
while fast!=None:
slow=slow.next
fast=fast.next
return slow
if __name__="__main__":
head=ConstructList() #链表头指针
result=None
prrnt "链表:",
PrintList(head)
result=FindLastK(head,3)
if result!=None:
print "\n链表倒数第3个元素为:"+str(result.data),
程序的运行结果为:
链表:1 2 3 4 5 6 7
链表倒数第3个元素为:5
算法性能分析:
这种方法只需要对链表进行一次遍历,因此,时间复杂度为O(N)。另外,由于只需要常量个指针变量来保存结点的地址信息,因此,空间复杂度为O(1)。
【答案解析】[考点] 如何找出单链表中的倒数第k个元素。