gpt4 book ai didi

c - 在不使用指向指针的指针的情况下反转链表

转载 作者:太空宇宙 更新时间:2023-11-04 05:08:43 25 4
gpt4 key购买 nike

我已经使用这段代码成功实现了 2 指针解决方案:

void list_reverse(t_list **begin_list)
{
t_list *new_root;
t_list *root;
t_list *next;

new_root = 0;
root = *(begin_list);
while (root)
{
next = root->next;
root->next = new_root;
new_root = root;
root = next;
}
*begin_list = new_root;
}

效果很好 - 至少根据我的测试。现在我想尝试仅使用单个指针来反转链表,而不使用 return,因此我尝试将我的代码转换为 void list_reverse(t_list *begin_list),但是当然 *begin_list = new_root 不起作用,因为我无法更改 begin_list。其余的似乎都有效。

如何在没有双指针的情况下修改 begin_list

编辑:结构是:

typedef struct  s_list
{
struct s_list *next;
void *data;
} t_list;

最佳答案

您可以通过交换第一个和最后一个节点(浅拷贝)来反转列表,然后反转列表。这样最后一个节点的内容将在头指针已经指向的初始节点中结束。

这是一个实现:

void swap(struct node *a, struct node *b) {
struct node tmp = *a;
*a = *b;
*b = tmp;
}

void reverse(struct node *h) {
// Null list and single-element list do not need reversal
if (!h || !h->next) {
return;
}
// Find the last node of the list
struct node *tail = h->next;
while (tail->next) {
tail = tail->next;
}
// Swap the tail and the head **data** with shallow copy
swap(h, tail);
// This is similar to your code except for the stopping condition
struct node *p = NULL;
struct node *c = tail;
do {
struct node *n = c->next;
c->next = p;
p = c;
c = n;
} while (c->next != tail);
// h has the content of tail, and c is the second node
// from the end. Complete reversal by setting h->next.
h->next = c;
}

Demo.

关于c - 在不使用指向指针的指针的情况下反转链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45270833/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com