输出单向链表倒数第k个节点,倒数第0个指向尾节点.
2016-07-07 16:10
423 查看
首先想到的是链表逆序, 然后输出第K个节点.
还可以先计算链表中节点个数n, 倒数第0个, 就是顺数第n - 0 -1个.
typedef struct ListNode{
int m_nKey;
struct ListNode * m_pNext;
}ListNode;
ListNode * retKNode(ListNode * list, int k)
{
int n = 0;
ListNode * current = list->m_pNext;
while(current)
{
n++;
current = current->m_pNext;
}
if(k < 0 || k >= n)
{
current = NULL;
}
else
{
int i;
current = list->m_pNext;
for(i = 0; i < n -k-1; i++)
{
current = current->m_pNext;
}
}
return current;
}
还可以先计算链表中节点个数n, 倒数第0个, 就是顺数第n - 0 -1个.
typedef struct ListNode{
int m_nKey;
struct ListNode * m_pNext;
}ListNode;
ListNode * retKNode(ListNode * list, int k)
{
int n = 0;
ListNode * current = list->m_pNext;
while(current)
{
n++;
current = current->m_pNext;
}
if(k < 0 || k >= n)
{
current = NULL;
}
else
{
int i;
current = list->m_pNext;
for(i = 0; i < n -k-1; i++)
{
current = current->m_pNext;
}
}
return current;
}
相关文章推荐
- C++继承与派生
- 修改Win7工具栏资源管理器打开后的默认路径
- 团体程序设计天梯赛-练习集L2-002. 链表去重
- 【bzoj2464】中山市选[2009]小明的游戏
- markdown文本居中,段首缩进的方法
- YL杯超级篮球赛 (Standard IO)
- EventBus sticky事件
- android studio 进行ndk开发思考总结
- ORA-04098: trigger 'SYS.OLAPISHUTDOWNTRIGGER' is invalid and failed re-validation
- 打包遇到错误:missing ios distribution signing identity for XXXXXXXXXX
- hdu 1050 Moving Tables
- navisworks 改变颜色没有反应
- SVN不需要上传哪些文件
- 抽象类和接口
- hibernate一对多关系映射时遇到的问题(Could not get constructor for org.hibernate.)
- AJAX教程系列一:环境安装及第一个ajax程序
- 关于dataGrid的排序自定义排序规则
- (03)Hibernate实现CRUD的案例
- Python的collections模块中namedtuple结构使用示例
- Kotlin Language Documentation for Kindle