📌  相关文章
📜  用于在给定大小的组中反转链表的 C 程序 – 第 1 组

📅  最后修改于: 2022-05-13 01:55:29.781000             🧑  作者: Mango

用于在给定大小的组中反转链表的 C 程序 – 第 1 组

给定一个链表,编写一个函数来反转每 k 个节点(其中 k 是函数的输入)。

例子:

算法反向(head,k)

  • 反转大小为 k 的第一个子列表。在反转时跟踪下一个节点和前一个节点。让指向下一个节点的指针为next ,指向前一个节点的指针为prev 。请参阅此帖子以反转链表。
  • head->next = reverse(next, k) (递归调用列表的其余部分并链接两个子列表)
  • 返回prevprev成为列表的新头部(参见本文的迭代方法图)

下图显示了反向函数的工作原理:

下面是上述方法的实现:

C
// C program to reverse a linked list
//  in groups of given size
#include
#include
  
// Link list node
struct Node
{
    int data;
    struct Node* next;
};
  
/* Reverses the linked list in groups 
   of size k and returns the pointer 
   to the new head node. */
struct Node *reverse (struct Node *head, 
                      int k)
{
    if (!head)
        return NULL;
    
    struct Node* current = head;
    struct Node* next = NULL;
    struct Node* prev = NULL;
    int count = 0;     
      
    /* Reverse first k nodes of the 
       linked list */ 
    while (current != NULL && count < k)
    {
        next  = current->next;
        current->next = prev;
        prev = current;
        current = next;
        count++;
    }
      
    /* next is now a pointer to (k+1)th node 
       Recursively call for the list starting 
       from current. And make rest of the list 
       as next of first node */
    if (next !=  NULL)
       head->next = reverse(next, k); 
  
    // prev is new head of the input list
    return prev;
}
  
// UTILITY FUNCTIONS
// Function to push a node 
void push(struct Node** head_ref, 
          int new_data)
{
    // Allocate node 
    struct Node* new_node =
           (struct Node*) malloc(sizeof(struct Node));
  
    // Put in the data    
    new_node->data  = new_data;
  
    // Link the old list off the 
    // new node 
    new_node->next = (*head_ref);    
  
    // Move the head to point to the 
    // new node 
    (*head_ref) = new_node;
}
  
// Function to print linked list
void printList(struct Node *node)
{
    while (node != NULL)
    {
        printf("%d  ", node->data);
        node = node->next;
    }
}    
  
// Driver code
int main(void)
{
    // Start with the empty list
    struct Node* head = NULL;
   
     // Create Linked list is 
     // 1->2->3->4->5->6->7->8->9 
     push(&head, 9);
     push(&head, 8);
     push(&head, 7);
     push(&head, 6);
     push(&head, 5);
     push(&head, 4);
     push(&head, 3);
     push(&head, 2);
     push(&head, 1);           
  
     printf("Given linked list ");
     printList(head);
     head = reverse(head, 3);
  
     printf("Reversed Linked list ");
     printList(head);
  
     return(0);
}


输出:

Given Linked List
1 2 3 4 5 6 7 8 9 
Reversed list
3 2 1 6 5 4 9 8 7 

复杂性分析:

  • 时间复杂度: O(n)。
    列表的遍历只进行一次,它有“n”个元素。
  • 辅助空间: O(n/k)。
    对于每个大小为 n、n/k 或 (n/k)+1 的链表,将在递归期间进行调用。

请参阅完整的文章在给定大小的组中反转链接列表 |设置 1 了解更多详情!