题目:输入一个单链表,并且输入k,求该链表中倒数第k个结点(倒数第0个节点是尾节点)。
算法思想:设置双指针,first和second,先让first指针从头开始遍历k个节点,然后让first继续遍历,second从头遍历(first和second同时遍历),当first遍历到链表的末尾,此时second指针所指向的正好是倒数第k个节点。
head-->1-->2-->3-->4-->5-->6-->7-->8-->9-->10-->NULL
其中倒数第0个节点是NULL,倒数第1个节点是10,倒数第10个节点是1
代码:
#include <iostream>
using namespace std;
typedef struct node
{
int value;
struct node* next;
}node_t;
void createLinkList(node_t* node)
{
if(node == NULL)
{
node = new node_t();
node->next = NULL;
}
}
void appendToListTail(node_t* head, int value)
{
if(head == NULL)
return;
node_t* temp = head;
while(temp->next != NULL)
{
temp = temp->next;
}
node_t* new_node = new node_t();
new_node->value = value;
new_node->next = NULL;
temp->next = new_node;
}
void printElements(node_t* head)
{
if(head == NULL)
return;
node_t* temp = head->next;
while(temp != NULL)
{
cout << temp->value << "-->";
temp = temp->next;
}
}
inline int getListLength(node_t* head)
{
int count = 0;
if(head == NULL)
return count;
node_t* temp = head->next;
while(temp != NULL)
{
++count;
temp = temp->next;
}
return count;
}
node_t* getTheLastKthNode(node_t *head, int k)
{
if(head == NULL)
return NULL;
int length = getListLength(head);
node_t* first = head;
int count = 0;
while(count < k)
{
if(first != NULL)
{
first = first->next;
++count;
}
else
{
}return NULL;
}
node_t* second = head;
while((first != NULL) && (second != NULL))
{
first = first->next;
second = second->next;
}
return second;
}
int main()
{
int value;
int count = 0;
node_t* head = new node_t();
head->next = NULL;
createLinkList(head);
cout << "输入10个元素加入链表:";
while(count < 10)
{
cin >> value;
appendToListTail(head, value);
count++;
}
cout << "链表元素为:";
printElements(head);
cout << endl;
int length = getListLength(head);
cout << "链表长度为:" << length << endl;
int k;
cout << "输入k,打印链表中倒数第k个节点:";
cin >> k;
if((k > length) || (k <= 0))
{
cout << "输入错误,k值范围(0," << length << "]" << endl;
}
else
{
node_t* result = getTheLastKthNode(head, k);
if(result != NULL)
cout << "链表中倒数第" << k << "个节点值是:" <<result ->value << endl;
else
cout << "节点为空!" << endl;
}
system("Pause");
return 0;
}