查找链表中倒数第k个节点元素

题目:输入一个单链表,并且输入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;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值