1. 程式人生 > >輸出連結串列倒數第k個數

輸出連結串列倒數第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");
}