【发布时间】:2017-11-07 15:48:38
【问题描述】:
谁能解释一下为什么函数 *kAltReverse 返回节点类型 prev 以及当您在 print 函数中调用 node->next 以从结构节点和打印中获取下一个元素时它将如何工作以及它如何指向下一个数据?
我不明白如何使用 *kAltReverse 函数中的 prev 打印数据?
非常感谢您的帮助!!!
问题来源:GeeksforGeeks
#include<stdio.h>
#include<stdlib.h>
struct node {
int data;
struct node* next; };
struct node *kAltReverse(struct node *head, int k) {
struct node* current = head;
struct node* next;
struct node* prev = NULL;
int count = 0;
while (current != NULL && count < k)
{
next = current->next;
current->next = prev;
prev = current;
current = next;
count++;
}
if(head != NULL)
head->next = current;
count = 0;
while(count < k-1 && current != NULL )
{
current = current->next;
count++;
}
if(current != NULL)
current->next = kAltReverse(current->next, k);
return prev;
}
void push(struct node** head_ref, int new_data) {
struct node* new_node =
(struct node*) malloc(sizeof(struct node));
new_node->data = new_data;
new_node->next = (*head_ref);
(*head_ref) = new_node;
}
void printList(struct node *node) {
int count = 0;
while(node != NULL)
{
printf("%d ", node->data);
node = node->next;
count++;
}
}
int main(void) {
struct node* head = NULL;
for(int i = 20; i > 0; i--)
push(&head, i);
printf("\n Given linked list \n");
printList(head);
head = kAltReverse(head, 3);
printf("\n Modified Linked list \n");
printList(head);
getchar();
return(0);
}
【问题讨论】:
-
根据我从代码中了解到的情况,该函数正在反转链表(或者,至少反转'k'元素)。基本上在while循环中,当前节点被下一个元素填充,当前节点保存在
prev中。因此,当您完成反转所有元素时,prev 中的值将成为您的新头。 (我不完全确定我所说的,但在我看来这就是代码正在做的事情) -
它看起来像一个程序来反转链表的第 1 k 个元素。
-
调试器非常适合理解发生了什么...当前程序反转链表的第 k 个元素,然后前进 k 个位置并从那里递归。最后你有 k 个元素反转,k 顺序,k 反转,...直到列表的末尾。
-
如果列表中的元素多于 k 就会泄露它们,对吧?
-
这段代码有效,它反转了 3 个节点的交替组,您只想知道它是如何通过从 kAltReverse 函数返回 prev 来工作的?
标签: c pointers linked-list