链表的倒数第k个元素(mark)
2016-04-20 00:23
295 查看
在之前创建的链表的基础上,访问链表的倒数第k个元素。
#include<iostream>
#include<cstring>
#include<vector>
#include<assert.h>
using namespace std;
struct ListNode
{
int m_key;
ListNode* next;
};
void createList1(ListNode* pHead)
{
ListNode* p=pHead;
for(int i=1;i<10;i++)
{
ListNode*pNewNode=new ListNode;
pNewNode->m_key=i;
pNewNode->next=NULL;
p->next=pNewNode;
p=pNewNode;
}
}
ListNode* FindKthNode(ListNode* pHead,int k)
{
ListNode* p1=pHead;
ListNode*p2=NULL;
for(int i=0;i<k-1;i++)
{
p1=p1->next;
}
p2=pHead;
while(p1->next!=NULL)
{
p1=p1->next;
p2=p2->next;
}
return p2;
}
int main()
{
ListNode*head=NULL;
head=new ListNode;
head->m_key=0;
head->next=NULL;
createList1(head);
ListNode* p=FindKthNode(head,2);
cout<<p->m_key<<endl;
while(head!=NULL)
{
cout<<head->m_key;
head=head->next;
}
cout<<endl;
}
#include<iostream>
#include<cstring>
#include<vector>
#include<assert.h>
using namespace std;
struct ListNode
{
int m_key;
ListNode* next;
};
void createList1(ListNode* pHead)
{
ListNode* p=pHead;
for(int i=1;i<10;i++)
{
ListNode*pNewNode=new ListNode;
pNewNode->m_key=i;
pNewNode->next=NULL;
p->next=pNewNode;
p=pNewNode;
}
}
ListNode* FindKthNode(ListNode* pHead,int k)
{
ListNode* p1=pHead;
ListNode*p2=NULL;
for(int i=0;i<k-1;i++)
{
p1=p1->next;
}
p2=pHead;
while(p1->next!=NULL)
{
p1=p1->next;
p2=p2->next;
}
return p2;
}
int main()
{
ListNode*head=NULL;
head=new ListNode;
head->m_key=0;
head->next=NULL;
createList1(head);
ListNode* p=FindKthNode(head,2);
cout<<p->m_key<<endl;
while(head!=NULL)
{
cout<<head->m_key;
head=head->next;
}
cout<<endl;
}
相关文章推荐
- 练习-登陆接口
- 进程的地址空间
- Linux dd——备份命令
- 进程—异常控制流之陷阱篇
- C++中class的类型转换重载
- 自定义弹窗 VS AlertDialog分享弹窗
- enumerate函数使用(增加列表,元组,字典,字符串等的下标)
- 备战找工作
- TCP笔记
- spring与hibernate整合之:继承HibernateDAOSupport方式+理解xml与AutoWired、Resource的区别
- WIFI WPA1/2 Crack for Windows
- 扯谈spring mvc之WebApplicationContext的继承关系
- FPGA第零篇:我的FPGA开发之旅
- 轻量级的无线抓包(microsoft network monitor)
- mysql函数concat与group_concat使用说明
- nginx配置
- 在线分享《从案例说InnoDB的基本优化》
- Scala for the Impatients---(5)Classes
- XML查询
- [RxJS] Combining streams in RxJS