输出链表倒数第k个数

// 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");
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值