问题:给定一个链表,写一个函数来逆转链表中的每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);
}