栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

手写代码:一个单向链表,给出头结点,找出倒数第N个结点,要求O(N)的时间复杂度?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

手写代码:一个单向链表,给出头结点,找出倒数第N个结点,要求O(N)的时间复杂度?

参考回答:

JAVA版本:

public class Solution {public ListNode FindNthToTail(ListNode head,int N) {ListNode pre=null,p=null;//两个指针都指向头结点p=head;pre=head;//记录N值int a=N;//记录节点的个数int count=0;//p指针先跑,并且记录节点数,当p指针跑了N-1个节点后,pre指针开始跑,//当p指针跑到最后时,pre所指指针就是倒数第N个节点while(p!=null){p=p.next;count++;if(N<1){pre=pre.next;}N--;}//如果节点个数小于所求的倒数第N个节点,则返回空if(count<a) return null;return pre;}}

 

C/C++版本:

class Solution {public:ListNode* FindNthToTail(ListNode* pListHead, unsigned int N) {if(pListHead==NULL||N==0)return NULL;ListNode*pTail=pListHead,*pHead=pListHead;for(int i=1;i<N;++i){if(pHead->next!=NULL)pHead=pHead->next;elsereturn NULL;}while(pHead->next!=NULL){pHead=pHead->next;pTail=pTail->next;}return pTail;}};Python:class Solution:def FindNthToTail(self, head, N):# write pre hereres=[]while head:res.append(head)head=head.nextif N>len(res) or N<1:returnreturn res[-N]

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/363546.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号