在 C++ 中查找从中间向链表头部方向的第 k 个节点

c++server side programmingprogramming

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

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

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

输出:7

解释:

中间节点值为 9。

从中间向头部的第二个节点为 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

相关文章