C - 链接列表:此功能的输出应该是什么?

时间:2017-06-09 19:20:09

标签: c list function

我坚持使用我在考试模拟中找到的这段代码:

struct node{
    int val;
    struct node* next;
};

struct node* list;

struct node* function (struct node* p){
       struct node *temp, *prec = NULL;
       if (p!=NULL){
          while(p->next!=NULL){
                temp=prec;
                prec=p;
                p=p->next;
                prec->next=temp;
                }
                p->next=prec;
       }
       return p;
    }

我试图编译它,显示的输出是反向列表。例如:如果我的列表由1,2,3和4组成。显示的输出是4,3,2和1.我的问题是:有人能解释我在while循环中发生了什么吗?

1 个答案:

答案 0 :(得分:0)

我已经重命名变量以使事情变得更清楚:

struct node* function (struct node* current_node){
   struct node *temp;            
   struct node *previous_node = NULL;
   if (current_node!=NULL){
    while(current_node->next!=NULL){
      temp                = previous_node;      //Save pointer to upstream node
      previous_node       = current_node;       //Make previous node the current node
      current_node        = current_node->next; //Move to the next node
      previous_node->next = temp;               //Set the previous node to point to the previous previous node
    }
    current_node->next=previous_node;           //Set final node to point to last previous node
  }
  return current_node;
}