/*
输入一个字符序列,生成带头结点的单链表,输入0表示结束,例如输入1230,则生成的单链表为->| | -> | 1 | -> | 2 | -> | 3 |。输出该链表中倒数第k个结点的值。
例如,输入:12548632102
输出:2
*/
#include <stdio.h>
#include <stdlib.h>
struct Node {
char data;
struct Node* next;
};
struct Node* create_node( char d, struct Node* n );
struct List {
struct Node* pHead;
struct Node* pTail;
int to_be_found_in_reverse;
};
void init_and_input( struct List* plist );
void output_and_destroy( struct List* pList );
void init( struct List* plist );
void destroy( struct List* plist );
void show( const struct List* pList );
int main() {
struct List list;
init_and_input( &list );
//show( &list );
output_and_destroy( &list );
}
void init_and_input( struct List* plist ) {
char tmp;
init( plist );
while( (tmp = getchar()) != '0' ) {
plist->pTail->next = create_node( tmp, NULL );
plist->pTail = plist->pTail->next;
}
scanf("%d",&plist->to_be_found_in_reverse);
}
struct Node* create_node( char d, struct Node* n ) {
struct Node* result;
result = (struct Node*)malloc( sizeof( struct Node ) );
result->data = d;
result->next = n;
return result;
}
void show( const struct List* pList ) {
const struct Node* p;
for( p = pList->pHead->next; p; p=p->next ) {
printf("%c",p->data);
}
printf("\n");
}
void output_and_destroy( struct List* pList ) {
const struct Node* p;
int total_step = 0;
int step;//正数的步数
int i;
for( p = pList->pHead->next; p; p=p->next ) {
++total_step;
}
step = total_step - pList->to_be_found_in_reverse;
for( p = pList->pHead->next,i=0; i<step; p=p->next,++i );
printf("%c\n",p->data);
destroy( pList );
}
void init( struct List* plist ) {
plist->pHead = create_node( 0, NULL );
plist->pTail = plist->pHead;
}
void destroy( struct List* plist ) {
struct List* tmp;
while( plist->pHead ) {
tmp = plist->pHead;
plist->pHead = plist->pHead->next;
free( tmp );
}
}
|