标签:求链表倒数第几个节点
使用两个指针,和判断一个链表是否形成环类似
代码:
#include <iostream>
#include <list>
using namespace std;
typedef struct node {
int data;
struct node *next ;
}Node,*pNode;
void creatNode( pNode &pHead ){
bool isFirst=true;
pNode p,q;
int temp;
scanf("%d",&temp);
while(temp){
p=(pNode)malloc(sizeof(Node));
p->data = temp;
p->next = NULL;
if(isFirst){
q=pHead=p;
isFirst = false;
}else{
q->next = p;
q = p;
}
scanf("%d",&temp);
}
}
void print(pNode p){
while(p){
cout<<p->data << " ";
p = p->next;
}
}
pNode printLast(pNode pHead,unsigned int m){
if(NULL == pHead || m==0)
return NULL ;
pNode pAhead = pHead;
pNode pBehind = pHead;
for(int i=1;i<=m;i++){
if(pAhead->next != NULL)
pAhead = pAhead->next;
else
return NULL;
}
while(pAhead){
pAhead = pAhead->next;
pBehind = pBehind->next;
}
return pBehind;
}
int main()
{
pNode pHead=NULL;
creatNode(pHead);
print(pHead);
cout<<endl<< printLast(pHead,2)->data;
return 0;
}
标签:求链表倒数第几个节点
原文地址:http://blog.csdn.net/buyingfei8888/article/details/38364305