C++中查找链表从中间到头的第k个节点


在这个问题中,我们给定一个链表和一个数字k。我们的任务是从链表的中间朝向头部查找第k个节点

让我们举个例子来理解这个问题:

输入:链表:4 -> 2 -> 7 -> 1 -> 9 -> 12 -> 8 -> 10 -> 5, k = 2

输出:7

解释:

中间节点的值是9。

从中间朝向头部,第2个节点是7。

解决方案

我们需要找到从链表中间到开头的第k个元素。为此,我们需要遍历链表从头到尾找到链表的大小。

从中间到开头的第k个元素是从开头数的第(n/2 + 1 - k)个元素。

程序演示了我们解决方案的工作原理:

示例

在线演示

#include <iostream>
using namespace std;

struct Node {
   int data;
   struct Node* next;
};

void pushNode(struct Node** head_ref, int new_data)
{
   struct Node* new_node = new Node;
   new_node->data = new_data;
   new_node->next = (*head_ref);
   (*head_ref) = new_node;
}

int findKmiddleNode(struct Node* head_ref, int k) {
   
   int n = 0;
   struct Node* counter = head_ref;
   while (counter != NULL) {
      n++;
      counter = counter->next;
   }
   int reqNode = ((n / 2 + 1) - k);

   if (reqNode <= 0)
      return -1;
     
   struct Node* current = head_ref;
   int count = 1;
   while (current != NULL) {
      if (count == reqNode)
         return (current->data);
      count++;
      current = current->next;
   }
}

int main()
{

   struct Node* head = NULL;
   int k = 2;
   pushNode(&head, 5);
   pushNode(&head, 10);
   pushNode(&head, 8);
   pushNode(&head, 12);
   pushNode(&head, 9);
   pushNode(&head, 1);
   pushNode(&head, 7);  
   pushNode(&head, 2);
   pushNode(&head, 4);

   cout<<k<<"th element from beginning towards head is "<<findKmiddleNode(head, k);

   return 0;
}

输出

2th element from beginning towards head is 7

更新于:2021年1月25日

374 次浏览

开启你的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.