题目:
输入一个单向链表,输出该链表中倒数第k个结点,
链表的倒数第1个结点为链表的尾指针。
题目分析:
题目分析:此题目不难,只需要定义两个链表的结点指针,分别指向头结点。
然后其中一个向前移动k-1步,然后这两个结点分别向后移动。一直到
前面的的指针移动到链表的尾指针位置。
我们看一下代码,头文件:
//
// 13th.h
// 100-alg-tests
//
// Created by bobkentt on 15-5-9.
// Copyright (c) 2015年 kedong. All rights reserved.
//
#ifndef ___00_alg_tests___3th__
#define ___00_alg_tests___3th__
#include <stdio.h>
struct Node
{
int value;
Node* next;
};
class List {
Node* m_head;
Node* m_tail;
public:
Node* insert(int value);
/*
* @param <k> <链表的倒数第几个元素>
* return <Node> <返回链表的倒数第k个结点地址>
*/
Node* find(int k);
List(int* arrary,int size);
~List() { };
};
int test_13();
#endif /* defined(___00_alg_tests___3th__) */
源码实现:
List::List(int* arrary,int size) {
for (int i = 0; i < size; i++) {
if (NULL == insert(arrary[i]))
return ;
}
}
Node* List::insert(int value) {
if (NULL == m_head) {
m_head = (Node*)malloc(sizeof(Node));
if (NULL == m_head) {
cout<<strerror(errno)<<endl;
}
m_head->value = value;
m_head->next = NULL;
m_tail = m_head;
return m_head;
}
if (NULL != m_tail) {
m_tail->next = (Node*)malloc(sizeof(Node));
if (NULL == m_tail->next) {
cout<<strerror(errno)<<endl;
}
m_tail = m_tail->next;
m_tail->value = value;
m_tail->next = NULL;
return m_tail;
}
cout<<"Insert error "<<endl;
return NULL;
}
Node* List::find(int k) {
if (NULL == m_head) {
return NULL;
}
Node* front = m_head;
Node* behind = front;
for (int i = 0; i < k - 1; i++) {
if (NULL == front->next) {
return NULL;
}
front = front->next;
}
for (int i = 0; ; i++) {
if (NULL == front->next) {
break;
}
front = front->next;
behind = behind->next;
}
return behind;
}
测试程序:
int test_13() {
#define ARRAY_LEN 100
int array[ARRAY_LEN];
for (int i = 0; i < ARRAY_LEN; i++) {
array[i] = i + 1;
}
List obj(array,ARRAY_LEN);
Node* element = obj.find(5);
cout<<element->value<<endl;
return 0;
}
我们看一下打印输出:
96
Program ended with exit code: 0