以每K个元素为一组逆转单链表
来源:互联网 发布:游戏录制视频软件 编辑:程序博客网 时间:2024/04/29 22:06
问题:给定一个链表,写一个函数来逆转链表中的每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);}
- 以每K个元素为一组逆转单链表
- 每间隔K个元素逆转一次单链表
- 以k个元素为一组反转单向链表
- 以k个元素为一组反转单向链表
- 以K大小为一组反转单链表
- [leetcode]Reverse Nodes in k-Group 反转以k个节点为一组的链表
- [LeetCode]—Reverse Nodes in k-Group 将链表以n个节点为一组进行逆序
- leetCode 25.Reverse Nodes in k-Group (以k个节点为一组反转链表) 解题思路和方法
- [LeetCode] Reverse Nodes in k-Group每k个一组翻转链表
- 将长字符串以逗号分隔为4个一组
- 单向链表每k个元素翻转一次。
- 单向链表每k个元素翻转一次。
- 4. Median of Two Sorted Arrays(hard)(lg(n+m),可以转化为求俩组数合并后第k个元素,通过递归去掉前面一部分不可能为第k个元素的一组数来实现)
- 有一个数组,数组中有13个元素,先将该数组进行分组,每3个元素为一组,分为若干组,最后用一个数组统一管理这些分组.(要动态创建数组)
- 有一个数组,数组中有13个元素,先将该数组进行分组,每3个元素为一组,分为若干组,最后用一个数组统一管理这些分组.(要动态创建数组).
- 有一个数组,数组中有13个元素,先将该数组进行分组,每3个元素为一组,分为若干组,最后用一个数组统一管理这些分组.(要动态创建数组).
- 有一个数组,数组中有13个元素,先将该数组进行分组,每3个元素为一组,分为若干组,最后用一个数组统一管理这些分组.(动态开辟)
- 有一个数组,数组中有13个元素,先将该数组进行分组,每3个元素为一组,分为若干组,最后用一个数组统一管理这些分组.(要动态创建数组).
- 点击切换图片
- $.get 获取一个文件的内容,
- PCB封装尺寸(转载)
- 图像特征汇总
- android 程序发布安装包
- 以每K个元素为一组逆转单链表
- java 到出word简历,表格中插入照片-------非常实用,copy下去就可以使用
- 《数据结构》之(散列表)
- hdu 4561 连续最大积
- 如何创造一个伟大的城市(How to make a city great)
- 支付宝支付功能集成
- 判断设备是否是 iphone5
- Android系统的改进(五)-- 没有精确的电量提醒功能
- DXUT11框架浅析(9)--DXUTDevice9