C 以迭代方式反转列表逻辑错误

C 以迭代方式反转列表逻辑错误,c,linked-list,C,Linked List,在这里,我尝试迭代地反转列表。但是问题是列表有多大,比如说3->2->4->NULL,最后它变成了3->NULL,即只有一个元素的列表。 请告诉我代码中有什么问题 struct node *reverselist(struct node *head) { struct node *list=head; if(head==NULL) { printf("\nThe list is empty\n"); return

在这里,我尝试迭代地反转列表。但是问题是列表有多大,比如说3->2->4->NULL,最后它变成了3->NULL,即只有一个元素的列表。 请告诉我代码中有什么问题

    struct node *reverselist(struct node *head)
{
     struct node *list=head;
     if(head==NULL)
     {
           printf("\nThe list is empty\n");
           return head;
     }
     if(head->next==NULL)
     {
           printf("\nThe list has only one element\n");
           return head;
     }
     struct node *cur=head;
     struct node *new=head->next;
     while(cur->next!=NULL)
     {
           cur->next=new->next;
           new->next=cur;
           new=cur->next;
         }
     return list;
}

您的逻辑错误-指针
new
正在正确更新,但
cur
已修复

而不是尝试此操作

struct node *reverselist(struct node *head)
{
    struct node *temp;
    struct node *newHead = NULL;
    struct node *curNode = head;

    while(curNode != NULL) {
        temp = curNode->next;
        curNode->next = newHead;
        newHead = curNode;
        curNode = temp;
    }

    return newHead;
}

您的逻辑错误-指针
new
正在正确更新,但
cur
已修复

而不是尝试此操作

struct node *reverselist(struct node *head)
{
    struct node *temp;
    struct node *newHead = NULL;
    struct node *curNode = head;

    while(curNode != NULL) {
        temp = curNode->next;
        curNode->next = newHead;
        newHead = curNode;
        curNode = temp;
    }

    return newHead;
}

您迭代cur->next并更改cur->next。所以,首先:你永远不会改变头,然后你把最后一个元素移到头之后的前面。

你迭代cur->next和change cur->next。所以首先:你永远不会改变头部,然后你把最后一个元素移到头部后面的前面。

不错。我不会使用head作为运行变量名。它混淆了事实reader@PeterMiehleThanx,是的,当我移动
头部时,它是不可读的,这有点混乱,我试图使其优化,我更喜欢使用额外的变量来移动头部,使其更可读。很好的一个。我不会使用head作为运行变量名。它混淆了事实reader@PeterMiehleThanx,是的,当我移动
头部时,它是不可读的,这有点混乱,我试图使它优化,我更喜欢使用额外的变量来移动头部,这样可以使头部更具可读性。我认为您键入错误-
afert
after
?我认为您键入错误-
afert
after