// ConsoleApplication4.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
typedef struct MyStruct
{
int data;
struct MyStruct* next;
}MyStruct;
int daoshu(MyStruct* A, int k)
{
MyStruct *p1 = A;
MyStruct *p2 = A->next;
int i=1; //统计遍历的元素个数
while (p2!=NULL) //P2遍历完成,此时P1在P2前面K个数,P1就是倒数第K个数
{
p2 = p2->next;
i++;
if (i > k) // 向后遍历K个数后,此时前一个指针也要随着动了
p1 = p1->next;
}
if (p1== A) //只有两种情况,P1一直没动,说明链表太短了,返回0;
return 0; //若是不等于第一个,因为P2已经遍历完成了,就返回此时P1的值
else
return p1->data;
}
MyStruct *create(int a[], int n)
{
MyStruct *r, *A;
A = (MyStruct*)malloc(sizeof(MyStruct));
A->next = NULL;
r = A;
for (int i = 0; i < n; i++)
{
MyStruct *s;
s = (MyStruct*)malloc(sizeof(MyStruct));
s->data= a[i];
r->next = s;
r = r->next;
}
r->next = NULL;
return A;
}
void print(MyStruct *L) //输出新链表
{
L = L->next;
printf("链表为");
while (L != NULL)
{
printf("%d ", L->data);
L = L->next;
}
printf("\n");
}
int _tmain(int argc, _TCHAR* argv[])
{
MyStruct *A;
int b;
int k = 5;
int a[8] = {12,34,56,986,323,135,32,23};
A = create(a,8);
print(A);
b = daoshu(A,k);
printf(" 倒数第%d个数是%d\n",k,b);
system("pause");
}
//
#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
typedef struct MyStruct
{
int data;
struct MyStruct* next;
}MyStruct;
int daoshu(MyStruct* A, int k)
{
MyStruct *p1 = A;
MyStruct *p2 = A->next;
int i=1; //统计遍历的元素个数
while (p2!=NULL) //P2遍历完成,此时P1在P2前面K个数,P1就是倒数第K个数
{
p2 = p2->next;
i++;
if (i > k) // 向后遍历K个数后,此时前一个指针也要随着动了
p1 = p1->next;
}
if (p1== A) //只有两种情况,P1一直没动,说明链表太短了,返回0;
return 0; //若是不等于第一个,因为P2已经遍历完成了,就返回此时P1的值
else
return p1->data;
}
MyStruct *create(int a[], int n)
{
MyStruct *r, *A;
A = (MyStruct*)malloc(sizeof(MyStruct));
A->next = NULL;
r = A;
for (int i = 0; i < n; i++)
{
MyStruct *s;
s = (MyStruct*)malloc(sizeof(MyStruct));
s->data= a[i];
r->next = s;
r = r->next;
}
r->next = NULL;
return A;
}
void print(MyStruct *L) //输出新链表
{
L = L->next;
printf("链表为");
while (L != NULL)
{
printf("%d ", L->data);
L = L->next;
}
printf("\n");
}
int _tmain(int argc, _TCHAR* argv[])
{
MyStruct *A;
int b;
int k = 5;
int a[8] = {12,34,56,986,323,135,32,23};
A = create(a,8);
print(A);
b = daoshu(A,k);
printf(" 倒数第%d个数是%d\n",k,b);
system("pause");
}