删除链表中每隔 K 个节点


在这篇文章中,我们将解释如何删除链表中每隔 K 个节点的方法。我们必须删除位于 K 的倍数位置上的每个节点,即,我们必须删除位置为 K、2*K、3*K 等的节点。

Input : 112->231->31->41->54->63->71->85
   k = 3
Output : 112->231->41->54->71->85
Explanation: As 3 is the k-th node after its deletion list would be :
First iteration :112->231->41->54->63->71->85
Now we count from 41 the next kth node is 63
After the second iteration our list will become : 112->231->41->54->71->85
And our iteration continues like this.

Input: 14->21->23->54->56->61
   k = 1
Output: Empty list
Explanation: All nodes need to be deleted

在这个问题中,我们将采用一种足够高效的常规方法,因此我们不需要对其进行优化。

解决方法

在这个问题中,我们将使用一个计数器遍历链表。如果计数器达到 K,我们删除该节点并将计数器重置为 1,以查找从当前节点开始的下一个第 K 个元素。

示例

#include<bits/stdc++.h>
using namespace std;
/* Linked list Node */
struct Node {
   int data;
   struct Node* next;
};
void push(struct Node** ref, int new_data) { // pushing the data into the list

   struct Node* new_n = new Node;
   new_n->data = new_data;
   new_n->next = (*ref);
   (*ref) = new_n;
}
void deletek(Node* prev, Node* curr) { // delete function

   if(prev == NULL) {
      prev = curr;
      curr = curr -> next;
      free(prev);
      prev = NULL;
   } else {
      prev -> next = curr -> next;
      auto tmp = curr;
      free(tmp); // freeing the space
   }
}
/* Function to print linked list */
void displayList(struct Node *head) {
   struct Node *temp = head;
   while (temp != NULL) {
      cout<<temp->data<<" ";
      temp = temp->next;
   }
}
// Function to create a new node.
struct Node *newNode(int x) {
   Node *temp = new Node;
   temp->data = x;
   temp->next = NULL;
   return temp;
}
int main() {
   struct Node* head = NULL;
   push(&head, 80);
   push(&head, 70);
   push(&head, 60);
   push(&head, 50);
   push(&head, 40);
   push(&head, 30);
   push(&head, 20);
   int k = 3; // given k
   Node* curr = head; // current pointer
   Node* prev = NULL; // previous pointer
   int count = 1; // position counter
   if(head == NULL || k == 0) // if list is already empty or k = 0
      cout << "Invalid\n";
   else {
      while(curr) { // traversing the list
         if(count == k) {
            deletek(prev, curr);
            curr = prev -> next;
            count = 1;
         } else {
            count++;
            prev = curr;
            curr = curr -> next;
         }
      }
      displayList(head); // printing the new list
   }
   return 0;
}

输出

20 30 50 60 80

上述方法的时间复杂度为 **O(N)**,其中 N 是给定链表的大小。

上述代码的解释

在上述方法中,我们首先掌握三件事:当前指针、前一个指针和位置计数器。当我们的位置计数器等于 K 时,我们删除一些节点,调用删除函数并将前一个和当前计数器作为参数,然后我们删除当前节点并释放空间。删除函数完成后,我们将当前指针移到下一个元素并将计数器重置为 1,并循环执行此块,直到我们的当前指针变为 NULL。

结论

在这篇文章中,我们解决了一个删除链表中每隔 K 个节点的问题。我们还学习了这个问题的 C++ 程序以及我们用来解决这个问题的完整方法(常规方法)。我们可以使用 C、Java、Python 等其他语言编写相同的程序。我们希望您觉得这篇文章有所帮助。

更新于:2021年11月26日

437 次浏览

开启您的 职业生涯

完成课程获得认证

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