【问题标题】:C - Linked lists: What should be the output of this function?C - 链表:这个函数的输出应该是什么?
【发布时间】:2017-06-09 19:20:08
【问题描述】:

我被我在考试模拟中发现的这段代码卡住了:

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 循环中发生了什么?

【问题讨论】:

  • 根据哪个规范正确?
  • 我测试中的问题是:根据输入中给出的列表,运行“list = function (list);”后的列表是什么声明?
  • 那么……你的“问题”不是在回答这个问题吗?
  • 当然,但我不明白为什么。 while 循环中的语句对我来说不是很清楚。
  • 拿一张纸,画一个清单,看看发生了什么,哪个变量指向哪里

标签: c list function


【解决方案1】:

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

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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-18
    • 1970-01-01
    相关资源
    最近更新 更多