[各种面试题] 链表相关
来源:互联网 发布:淘宝怎么修改商品类目 编辑:程序博客网 时间:2024/05/29 14:13
1.判断是否有环
bool existCircle(ListNode* head){if(!head)return false;ListNode* pSlow=head;ListNode* pFast=head->next;while(pFast!=NULL){if ( pSlow==pFast )return true;pSlow=pSlow->next;pFast=pFast->next;if (pFast)pFast=pFast->next;}return false;}
2.找环的起始位置
这个在纸上画个环就能看出相遇的地方到起始位置与表头到起始位置的距离是相等的。所以相遇后把一个放到头去再相遇就好了。
ListNode* findCircleStart(ListNode* head){if(!head)return NULL;ListNode* pSlow=head;ListNode* pFast=head->next;while(pFast!=NULL){if ( pSlow==pFast ){pSlow=head;while(pSlow!=pFast){pSlow=pSlow->next;pFast=pFast->next;}return pSlow;}pSlow=pSlow->next;pFast=pFast->next;if (pFast)pFast=pFast->next;}return NULL;}
3.反转链表
ListNode* reverseList(ListNode* head){if (!head || !head->next )return head;ListNode* Guard=new ListNode(-1,NULL);ListNode* pCur=head;while(pCur){ListNode* pTemp=pCur->next;pCur->next=Guard->next;Guard->next=pCur;pCur=pTemp;}ListNode* newHead=Guard->next;delete Guard;Gurad=0;return newHead;}
4.删除中间节点
同样用快慢指针即可。
void removeMiddle(ListNode*& head){if (!head )return ;ListNode* pPre=NULL;ListNode* pSlow=head;ListNode* pFast=head->next;while( pFast ){pPre=pSlow;pSlow=pSlow->next;pFast=pFast->Next;if (pFast)pFast=pFast->next;}if ( pPre==NULL ) //head is middle{head=pSlow->next;}else{pPre->next=pSlow->next;}delete pSlow;pSlow=0;}
5.倒数第K个节点
ListNode* findKthFromBack(ListNode* head,int k){assert(k>0); //last one is the 1st nodeListNode* pForward=head;while(pForward&&k){pForward=pForward->next;k--;}if ( k>0 )return NULL;ListNode* pBack=head;while(pForward){pForward=pForward->next;pBack=pBack->next;}return pBack;}
- [各种面试题] 链表相关
- 链表相关面试题
- 链表相关面试题
- 链表相关面试题
- 链表相关面试题
- 链表相关面试题
- [各种面试题] 链表归并排序
- 链表相关面试题(zz)
- 常见的链表相关面试题
- 链表相关的面试题总结
- 链表的相关面试题
- 链表相关面试题(一)
- 链表相关面试题(二)
- 链表的相关面试题
- 链表相关面试题总结大全
- C++面试题(三)——STL相关各种问题
- [各种面试题] 合并k个排序链表
- [各种面试题] 复制带随机节点的链表
- TMS和WMTS大概对比
- Win32App绘制封闭图形函数
- ios share with facebook/twitter, addthis library
- Ubuntu12.10 下搭建基于KVM-QEMU的虚拟机环境(十七)
- [Android开发常见问题-10]PagerTabStrip和PagerTitleStrip异同
- [各种面试题] 链表相关
- 重定向 1>&2 2>&1
- C++中实现回调机制的几种方式
- 分组背包+树形DP(BY LPX)
- 分布式存储系统设计 反熵 (Anti-Entropy)
- DP中的LIS:longest increasing subsequence
- 从今天开始写博客
- 关于C++中数据基础数据类型的一个杂记
- eclipse svn 切换: eclipse svn 切换项目svn地址