1.用C语言给定一个单链表的头结点head,实现一个调整单链表的函数,使得k个结点之 间逆序,如果最后一组不够k个节点,则不调整最后几个结点。要求:如果链 表的长度为N;时间复杂度达到O(N)。 例如: 链表:1->2->3->4->5->6->7->8->nul;k=3。 调整后:3-≥2-≥1-5->5-≥4-≥7->8->nu1l。并用主函数验证
时间: 2023-05-14 22:06:11 浏览: 403
以下是用C语言实现调整单链表的函数,使得k个结点之间逆序,时间复杂度为O(N):
```
#include <stdio.h>
#include <stdlib.h>
typedef struct ListNode {
int val;
struct ListNode *next;
} ListNode;
ListNode* reverseKGroup(ListNode* head, int k) {
if (head == NULL || k == 1) {
return head;
}
ListNode *dummy = (ListNode *)malloc(sizeof(ListNode));
dummy->next = head;
ListNode *pre = dummy, *cur = head;
int len = 0;
while (cur != NULL) {
len++;
cur = cur->next;
}
while (len >= k) {
cur = pre->next;
for (int i = 1; i < k; i++) {
ListNode *next = cur->next;
cur->next = next->next;
next->next = pre->next;
pre->next = next;
}
pre = cur;
len -= k;
}
return dummy->next;
}
int main() {
ListNode *head = (ListNode *)malloc(sizeof(ListNode));
head->val = 1;
head->next = (ListNode *)malloc(sizeof(ListNode));
head->next->val = 2;
head->next->next = (ListNode *)malloc(sizeof(ListNode));
head->next->next->val = 3;
head->next->next->next = (ListNode *)malloc(sizeof(ListNode));
head->next->next->next->val = 4;
head->next->next->next->next = (ListNode *)malloc(sizeof(ListNode));
head->next->next->next->next->val = 5;
head->next->next->next->next->next = (ListNode *)malloc(sizeof(ListNode));
head->next->next->next->next->next->val = 6;
head->next->next->next->next->next->next = (ListNode *)malloc(sizeof(ListNode));
head->next->next->next->next->next->next->val = 7;
head->next->next->next->next->next->next->next = (ListNode *)malloc(sizeof(ListNode));
head->next->next->next->next->next->next->next->val = 8;
head->next->next->next->next->next->next->next->next = NULL;
int k = 3;
ListNode *newHead = reverseKGroup(head, k);
while (newHead != NULL) {
printf("%d->", newHead->val);
newHead = newHead->next;
}
printf("null\n");
return 0;
}
```
关于第二个问题,"lua closure factory 完整代码",以下是一个简单的Lua闭包工厂的完整代码:
```
function createClosure(x)
return function(y)
return x + y
end
end
closure1 = createClosure(1)
closure2 = createClosure(2)
print(closure1(2)) -- 输出3
print(closure2(3)) -- 输出5
```
第三个问题,"中文加密",这个问题比较宽泛,不知道你具体想问什么。如果你想了解中文加密的一些常见方法,可以参考以下链接:
https://zh.wikipedia.org/wiki/%E4%B8%AD%E6%96%87%E5%8A%A0%E5%AF%86
https://blog.csdn.net/qq_35644234/article/details/60870728
https://www.cnblogs.com/zhengyun_ustc/p/10556394.html
阅读全文