您的位置:首页 > 其它

求单向链表倒数第k个节点

2013-12-02 12:57 190 查看
http://www.csdn123.com/html/blogs/20130602/18722.htm

/********************************************
题目:输入一个单向链表,输出该链表中倒数第k个结点。
链表的倒数第0个结点为链表的尾指针。
我们在遍历时维持两个指针,第一个指针从链表的头指针开始遍历,
在第k-1步之前,第二个指针保持不动;在第k-1步开始,
第二个指针也开始从链表的头指针开始遍历。由于两个指针的距离保持在k-1,
当第一个(走在前面的)指针到达链表的尾结点时,
第二个指针(走在后面的)指针正好是倒数第k个结点。
**********************************************/

#include<iostream>
using namespace std;

typedef struct node
{
int data;
struct node *next;
}Node,*List;

List createList(int N)
{
List head = new node;
head->data = 0;
head->next=NULL;
int count = 1991;
List p = head;
while(count<N+1991)
{
count++;
List s = new node;
s->data = count;
s->next = NULL;
p->next = s;
p = s;
}
return head;
}

void traverse(List head)
{
if(head == NULL)
{
return;
}
List p = head->next;
while(p)
{
cout<<p->data<<" ";
p = p->next;
}
cout<<endl;
}

List find(List head,int index)
{
int count = 0;
List first = head;
List second = NULL;
while(first&&count<index)//first首先找到第index个元素
{
first = first->next;
count++;
}

if(first!=NULL)//如果没有到链表尾
{
second = head;
while(first!=NULL)
{
first = first->next;
second = second->next;
}
}
return second;
}

int main()
{
int N = 22,n;
List head = createList(N);
traverse(head);
cout<<"请输入要查询倒数第几个数:"<<endl;
while(cin>>n)
{
List num = find(head,n);
if(num!=NULL)
{
cout<<"倒数第"<<n<<"个数是 :"<<num->data<<endl;
}
else
{
cout<<"没有这个数(输入数据大于链表长度)"<<endl;
}
cout<<"请输入要查询倒数第几个数:"<<endl;
}
return 0;
}
/****************************
运行结果:
1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007
2008 2009 2010 2011 2012 2013
请输入要查询倒数第几个数:
1
倒数第1个数是 :2013
请输入要查询倒数第几个数:
2
倒数第2个数是 :2012
请输入要查询倒数第几个数:
10
倒数第10个数是 :2004
请输入要查询倒数第几个数:
19
倒数第19个数是 :1995
请输入要查询倒数第几个数:
22
倒数第22个数是 :1992
请输入要查询倒数第几个数:
23
没有这个数(输入数据大于链表长度)
请输入要查询倒数第几个数:
44
没有这个数(输入数据大于链表长度)
请输入要查询倒数第几个数:
^Z

******************************/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: