首页 技术 正文
技术 2022年11月11日
0 收藏 839 点赞 4,663 浏览 1128 个字

链表中倒数第K个结点 牛客网 程序员面试金典 C++ Python

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

C++

/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
//run:3ms memory:476k
ListNode* FindKthToTail(ListNode* pListHead, unsigned int k) {
if(NULL == pListHead) return NULL;
if(0 == k) return NULL;
ListNode* p = pListHead;
ListNode* res = pListHead;
for(unsigned int i = 0; i< k; i++)
if (p) p=p->next;
else return NULL;
for(;p;p=p->next)
res = res->next;
return res;
} ListNode* FindKthToTail2(ListNode* pListHead, unsigned int k) {
if(NULL == pListHead) return NULL;
if(0 == k) return NULL;
ListNode* p = pListHead;
ListNode* res = pListHead;
for(unsigned int i = 0; i< k; i++)
if (p) p=p->next;
else return NULL;
while(p) {
res = res->next;
p = p->next;
}
return res;
}
};

Python

# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = Noneclass Solution:
#run:33ms memory:5728k
def FindKthToTail2(self, head, k):
if k<=0 or head == None:
return None
p = head
ret = head
for i in range(k):
if p:p = p.next
else:return None
while(p):
p = p.next
ret = ret.next
return ret #run:22ms memory:5852k
def FindKthToTail(self, head, k):
if k<=0 or head == None:
return None
else:
count = 0
p = head
ret = head
while p!=None:
count = count + 1
if count > k:
ret=ret.next
p = p.next
if count < k:
ret = None
return ret
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,031
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,520
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,368
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,148
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,781
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,860