反向链接的修补程序

问题描述 投票:0回答:2

嘿,由于某些原因,我的链表是按反向顺序打印的,例如,如果我输入的是2-> 4-> 6我的输出是6-> 4-> 2

list* add_int_list(list* a,int b)
{
    list *temp;
    temp = (list*)malloc(sizeof(list*));
    temp->next = NULL;
    if (a->next == NULL)//insert to the first node
    {
        temp->data = b;
        temp->next = a;
        a = temp;

    }
    else 
    {
        temp->data = b;
        temp->next = a;
        a = temp;//I think the problem is here, couldnt find how to fix 
}
c linked-list reverse
2个回答
0
投票

问题是,在两种情况下,您的代码都将节点附加到列表的开头。如果要始终追加到列表的末尾,则需要遍历列表直到末尾,然后在其中添加temp

我是随手编写的,因此将其作为伪代码:

// Assuming this function returns the front (head) of the list.
list* append_element_to_list(list* a, int b)
{
    list *newNode;
    newNode = (list*)malloc(sizeof(list*));
    newNode->data = b;

    // Handle the case where `a` is NULL. This means
    // no list was passed in, so the newly created node
    // will be returned to start the list.
    if (a == NULL)
    {
      return newNode;
    }

    // If we get this far, it means `a` contains at least
    // one node. So walk the list until the end.
    list *currentNode = a;
    while (currentNode->next != NULL)
    {
      currentNode = currentNode->next;
    }

    // Once you reach the end of the list, set
    // `newNode` as the last node.
    currentNode->next = newNode;

    // The front of the list hasn't changed, so return that.
    return a;
}

0
投票

您的代码中有一些错误,我正在对您的代码进行更正,只是更改了所需的内容。首先,我要关注主要问题,在插入任何列表的最后之前,您应该迭代整个列表。

  i = a; // to iterate
  while(i->next != NULL)
  {
   i = i->next;
  }
  // Now i is last node of list a
  i->next = temp;

现在下面的代码,我只是在TurboC上检查它,我正在使用您的函数并插入三个值,然后打印列表。请查看所有行注释:

#include <stdio.h>
#include <malloc.h>
typedef struct node{
 int data;
 struct node *next;

}list;

list* add_int_list(list* a,int b)
{
    list *temp;
    list *i;

    temp = (list*)malloc(sizeof(list*));
    temp->next = NULL;
    temp->data = b;

    if (a == NULL)//insert to the first node
    {
       //temp->data = b; -  done above
    //temp->next = a; no reason for this line
        a = temp;
    }
    else
    {
       // temp->data = b; - done above
       //temp->next = a; wrong logic
       // a = temp;//I think the problem is here, couldnt find how to fix : Yes it is also wrong

      //Here it required to iterate complete list and go to end

      i = a; // to iterate
      while(i->next != NULL)
      {
       i = i->next;
      }
      // Now i is last node of list a
      i->next = temp;
    }

    return a;
}
void printList(list *root)
{
   list *i;

   if(root->data == NULL)
   {
    printf("List is empty");
   }
   else
   {
    i = root;
    while(i->data != NULL){
      printf("%d,",i->data);
      i = i->next;
    }
   }
}
int main()
{
  list *root = NULL;
  clrscr();
  root =  add_int_list(root, 3);
  root =  add_int_list(root, 4);
  root =  add_int_list(root, 5);
  printList(root);
    return 0;
}
© www.soinside.com 2019 - 2024. All rights reserved.