找出链表中倒数第 k 个结点
2024-08-21 22:26:05
/*
题目:输入一个单向链表,输出该链表中倒数第 k 个结点。链表的倒数第 0 个结点为链表
的尾指针。
链表结点定义如下:
struct node
{
int data;
struct node *next;
};
typedef struct node* PtrToNode;
typedef PtrToNode Position;
typedef Position List;
*/
#include <iostream>
#include <assert.h>
#include "./List.h"
using namespace std;
void print_list(List list)
{
assert(list != NULL);
list = First(list);
while(list != NULL)
{
cout<<list->data<<" ";
list = list->next;
}
cout<<endl;
}
Position get_last_kth(List list, int k)
{
assert(list != NULL);
Position tmp = First(list);
while(tmp != NULL && --k >= )
tmp = tmp->next;
if(NULL == tmp)//the length of list <= k
return NULL;
Position ret = First(list);
while(tmp != NULL)
{
ret = ret->next;
tmp = tmp->next;
}
return ret;
}
int main(int argc, char const *argv[])
{
List list = CreateEmptyList();
int k;
for(int i = ; i != ; ++i)
PushBack(i, list);
print_list(list);
while(cin>>k)
{
Position tmp = get_last_kth(list, k);
cout<<"k:"<<k<<" = ";
if(tmp == NULL)
cout<<"NULL";
else
cout<<tmp->data;
cout<<endl;
}
return ;
}
最新文章
- Xamarin 跨移动端开发系列(01) -- 搭建环境、编译、调试、部署、运行
- Scrum Meeting 10-20151216
- Android 之 2048 的游戏逻辑分析
- linux下MYSQL备份与恢复
- 对js原型的理解
- 智能指针(二):shared_ptr实现原理
- Toad for Oracle 快捷键
- nginx 调优
- 《javascript高级程序设计》对象图
- 清空DNS缓存
- Solr学习(2) Solr4.2.0+IK Analyzer 2012
- Weex-语法笔记 一
- 【转】SWT/JFace的对话框
- ASP.NET Web API 2 消息处理管道
- Visual Studio Many Projects in One Solution VS中多工程开发
- Python云图——WordCloud了解一下
- IntelliJ IDEA 中SpringBoot对Run/Debug Configurations配置 SpringBoot热部署
- css 利用border 绘制三角形. triangle
- 动态添加布局、动态添加View、LinearLayout动态添加View;
- Python 通过gevent实现协程