以每K个元素为一组逆转单链表

问题:给定一个链表,写一个函数来逆转链表中的每K个节点,K是一个给定的值。

例如:

输入:  1->2->3->4->5->6->7->8->NULL and k = 3 
输出:  3->2->1->6->5->4->8->7->NULL. 

输入:   1->2->3->4->5->6->7->80->NULL and k = 5
输出:  5->4->3->2->1->8->7->6->NULL. 

#include <stdio.h>
#include <stdlib.h>
 
/* 链表节点 */
typedef struct node
{
    int data;
    struct node* next;
}node,*List;
 
/* 以k个元素为一组逆转链表并返回指向新的头结点的指针. */
List reverse (List head, int k)
{
    List current = head;
    List next;
    List prev = NULL;
    int count = 0;   
     
    /*逆转链表中的前K个节点 */
    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(List* head_ref, int new_data)
{
    /* allocate node */
    List new_node = (List) malloc(sizeof(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;
}
 
/* 打印链表节点 */
void printList(List node)
{
    while(node != NULL)
    {
        printf("%d  ", node->data);
        node = node->next;
    }
}    
 
/* 编写程序测试函数 */
int main(void)
{
    /* 空链表开始 */
    List head = NULL;
  
     /* 创建的链表为: 1->2->3->4->5->6->7->8 */
     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 \n");
     printList(head);
    
	 head = reverse(head, 3);
 
     printf("\nReversed Linked list \n");
     printList(head);
 
     getchar();
     return(0);
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值