1. 程式人生 > >輸出單鏈表倒數第K個結點值

輸出單鏈表倒數第K個結點值

倒數 else stdio.h cout size ++ iostream 鏈表 create

#include<iostream>
using namespace std;
#include<malloc.h>
#include<stdio.h>
typedef int Elem;
typedef struct AA{
Elem data;
struct AA *next;
}A;
void Create(A *&L,Elem a[],int n)
{
A *r,*s;
L=(A *)malloc(sizeof(A));
r=L;
for(int i=0;i<n;i++)
{
s=(A *)malloc(sizeof(A));

s->data=a[i];
r->next=s;
r=s;
}
r->next=NULL;
}
void DisPlay(A *L)
{
A *p=L->next;
while(p!=NULL){
cout<<p->data<<" ";
p=p->next;
}
cout<<endl;
}
void count1(A *L,int j,int n)
{
A *p=L->next;
int i=0;
while(p!=NULL&&n-j!=i)
{
i++;
p=p->next;
}
cout<<p->data<<endl;
}
int main()
{
A *s1;
Elem a[30];
int i;
for(i=0;i<30;i++)
{
cin>>a[i];
if(getchar()!=‘\n‘)
continue;
else
break;
}
Create(s1,a,i+1);
DisPlay(s1);
count1(s1,3,i+1);
}

輸出單鏈表倒數第K個結點值