链表常见问题:
#include<iostream>
#include<algorithm>
#include<cstdio>
#include<stack>
using namespace std;
struct ListNode
{
int key;
ListNode *p_next;
};
int GetListNodeNum(ListNode *p)//数量
{
int num=0;
while(p!=NULL)
{
num++;
p=p->p_next;
}
return num;
}
ListNode *ReverseList(ListNode *p)//反转
{
ListNode *R=NULL,*q;
while(p!=NULL)
{
q=p;
p=p->p_next;
q->p_next=R;
R=q;
}
return R;
}
void Look(ListNode *p)//输出
{
while(p!=NULL)
{
cout<<p->key<<" ";
p=p->p_next;
}
cout<<endl;
}
ListNode* Build(int n)//输入
{
ListNode *p=NULL,*q=NULL;
while(n--)
{
ListNode *s=new ListNode;
if(p==NULL)
{
p=s;
q=s;
}
else
{
q->p_next=s;
q=s;
}
scanf("%d",&s->key);
}
return p;
}
void Find(ListNode *p,int k)//逆序第k个
{
ListNode *s=p;
int n=1;
while(s!=NULL&&n<k)
{
n++;
s=s->p_next;
}
while(s->p_next!=NULL)
{
s=s->p_next;
p=p->p_next;
}
cout<<"k:"<<p->key<<endl;
}
void RePrintList(ListNode *p)//逆序输出
{
stack<ListNode*>L;
while(p!=NULL)
{
L.push(p);
p=p->p_next;
}
while(!L.empty())
{
p=L.top();
cout<<p->key<<" ";
L.pop();
}
cout<<endl;
}
int main()
{
int n;
while(cin>>n)
{
ListNode *p= Build(n);
cout<<GetListNodeNum(p)<<endl;
Look(p);
p=ReverseList(p);
Look(p);
RePrintList(p);
Find(p,1);
}
}